Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Submitting Forms with Mechanize (Python)

Well, I am trying to login to a site using Python and mechanize.

I've got the site opened:

site = br.open("http://example.com/login.php")

And I've got a list of the forms (with br.forms).

<GET http://example.com/search.php application/x-www-form-urlencoded
<HiddenControl(search=1) (readonly)>
...
<POST http://example.com/login.php application/x-www-form-urlencoded
<TextControl(username=)>
<PasswordControl(password=)>
<CheckboxControl(stay=[1])>
<SubmitControl(<None>=Log in) (readonly)>>

I've been trying to submit the username and password fields.

I tried doing it like this:

br.select_form(nr=0)
br.form["username"] = 'usernamehere'
br.form["password"] = 'passwordhere'
br.submit()

Then I realised that the forms I were trying to fill in weren't the first on the page, but changing the 0 didn't help with anything. What should I do for selecting the form on a page like this?

However! That is not the only problem.

When I run it, I get this error:

Traceback (most recent call last):
File "C:\Python26\login.py", line 34, in <module>
br.form["username"] = 'usernamehere'
...
ControlNotFoundError: no control matching name 'username'

How can I fix this? D: Or am I doing it totally wrong? If it's the latter, how would I go about doing it?

like image 523
Matthew Avatar asked Dec 20 '11 04:12

Matthew


1 Answers

to select a form using its name you should use:

br.select_form(name="order")

what you are doing here:

br.form["username"] = 'usernamehere'

is trying to set a value to a control under the selected form, so when he can't find it, it throws the exception you are seeing.

like image 162
tovmeod Avatar answered Oct 14 '22 20:10

tovmeod