【问题标题】:Python - Mechanize input text in formPython - 在表单中机械化输入文本
【发布时间】:2014-11-21 05:14:13
【问题描述】:

我想在表单的文本字段中输入一些文本。这是我当前的代码。接下来我该怎么办?

import re
from mechanize import Browser

br = Browser()
br.open("xyz.com")
formcount=0
for frm in br.forms():  
if str(frm.attrs["id"])=="xyz":
break
formcount=formcount+1
br.select_form(nr=formcount)

## What should I code here to input text into the form?

response = br.submit() 

【问题讨论】:

    标签: python forms mechanize


    【解决方案1】:
    br.form['id'] = 'ss-form' # This does the input
    br.submit() # This will submit the form
    print br.response().read() # This will read the new page returned
    

    试试print br.response().read()。这就是你想要的,你可以用 Beautiful Soup 解析响应。 soup = BeautifulSoup(br.response().read())

    【讨论】:

    • br.form['id'] = 'ss-form' 不适用于输入。这就是我得到的 - 文件“/usr/lib/python2.7/dist-packages/mechanize/_form.py”,第 3101 行,在 find_control return self._find_control(name, type, kind, id, label, predicate, nr) 文件“/usr/lib/python2.7/dist-packages/mechanize/_form.py”,第 3185 行,在 _find_control 中引发 ControlNotFoundError("no control matching"+description) mechanize._form.ControlNotFoundError: no control matching name 'ss-form'
    • 我正在设法提交一个空表单,但无法提交任何文本。也许现在你得到了我想做的事?
    • 这意味着表单没有该控件。您首先必须通过br.select_form( 'name_of_the_form' ) 选择正确的表格。
    • 使用for form in br.forms(): print form 查找所有表单的名称及其包含的内容。然后在使用之前选择正确的表格br.form['id'] = 'abc'
    • 表单未命名。这就是我尝试使用 id 的原因。另外,我认为我正确选择了表单,因为它已正确提交。
    【解决方案2】:

    如果表单未命名,您可以使用:

    br.select_form(nr=0)
    

    这将选择第一种形式(“第 0 个”)。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-09-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-09-13
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多