使用Mechanize提交表单(Python)

Mat*_*hew 8 python forms login mechanize

好吧,我正在尝试使用Python登录网站并进行机械化.

我打开了网站:

site = br.open("http://example.com/login.php")
Run Code Online (Sandbox Code Playgroud)

我有一个表单列表(使用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)>>
Run Code Online (Sandbox Code Playgroud)

我一直在尝试提交用户名和密码字段.

我尝试这样做:

br.select_form(nr=0)
br.form["username"] = 'usernamehere'
br.form["password"] = 'passwordhere'
br.submit()
Run Code Online (Sandbox Code Playgroud)

然后我意识到我试图填写的表单不是页面上的第一个,但更改0对任何事都没有帮助.如何在这样的页面上选择表单?

然而!这不是唯一的问题.

当我运行它时,我收到此错误:

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

我怎样才能解决这个问题?D:或者我完全错了吗?如果是后者,我该怎么做呢?

tov*_*eod 4

要使用名称选择表单,您应该使用:

br.select_form(name="order")
Run Code Online (Sandbox Code Playgroud)

你在这里做什么:

br.form["username"] = 'usernamehere'
Run Code Online (Sandbox Code Playgroud)

正在尝试为所选表单下的控件设置一个值,因此当他找不到它时,它会抛出您所看到的异常。