如何在 python 中使用 mechanize 确定 nr 值

How to determine nr value using mechanize in python

我正在编写脚本来登录网站。看下面的脚本

import mechanize
browser = mechanize.Browser()

print "Login to myweb"

browser.open('https://www.example.com/index.php/devicelogin')

#Login page. Give user credentials 
browser.select_form(nr=0)
browser.form["username"] = 'username'
browser.form["passwd"] = 'password'
browser.submit()

html = browser.response().read()

print html

当我 运行 它给我错误。

Login to myweb
Traceback (most recent call last):
  File "test.py", line 10, in <module>
  browser.form["username"] = 'username'
  File "build\bdist.win32\egg\mechanize\_form.py", line 2780, in __setitem__
  File "build\bdist.win32\egg\mechanize\_form.py", line 3101, in find_control
  File "build\bdist.win32\egg\mechanize\_form.py", line 3185, in _find_control
mechanize._form.ControlNotFoundError: no control matching name 'username'

现在,如果我在 browser.select_form(nr=0) 中更改 nr=1,那么它工作正常。

那么我如何确定 nr 值?

来自机械化source code

nr, if supplied, is the sequence number of the form (where 0 is the first).

所以页面中的第一个表格是0,第二个是1,第三个是2,等等

但是,如果您无法通过计数来确定表格的数量并且表格没有名称,您可以这样做:

for n in range(len(browser.forms())):
   browser.select_form(nr=n)
   try:
       browser.form["username"] = 'username'
       browser.form["passwd"] = 'password'
       browser.submit()
   except mechanize._form.ControlNotFoundError:
       continue  # check next form
   break 

html = browser.response().read()      

如果是命名表单,您可以跳过所有计数并通过简单地调用 browser.select_form('my_form_name')

来检索它

最后,如果您的表单没有名称属性并且您不想遍历表单,您可能想看看 Mechanicalsoup,它为您提供了以下可能性像使用 BeautifulSoup(因为它是基于它构建的)和类似 Mechanize 的 API.

一样浏览文档