【问题标题】:Python Mechanize module, selecting all input fields within a formPython Mechanize 模块,选择表单中的所有输入字段
【发布时间】:2011-12-17 01:25:51
【问题描述】:

我需要 Mechanize 将某个字符串放入所选范围内的每个可编辑输入字段中。以下是一些 HTML 代码作为示例:

<form action = "http://localhost/whatever.php" method = "post">
<input type = "hidden" name = "dummy" value = "12345">
<input type = "text" name = "msg"> <br/>
<input type = "text" name = "name"> <br/>
<input type = "submit" value = "Send">
</form>

由于在每个网站上重写我的 Python 脚本会非常乏味,并且会变得非常依赖于网站,我希望它在选定的表单中选择所有可编辑的输入字段(而不是编辑隐藏或禁用的字段)并设置每个输入字段的值到某个字符串。但是,我不会知道每个输入元素的名称。那么有没有一种方法可以通过索引号选择输入元素?到目前为止,我的代码看起来像这样:

import mechanize
browser = mechanize.Browser()
url = raw_input("Enter web address: ")
browser.open(url)
browser.select_form(nr=0)
# I know the index number of the form or my Python code will find out which it is
# but I do not know the names of the input elements within this form

那时,我想做这样的事情:找出有多少可编辑的输入元素存在,并通过其索引号选择每个元素,并将其设置为一个值。所以可以 这能做到吗?我只需要一种自动化的方式来选择输入字段并将它们设置为一个值,而无需知道它们的名称或 ID。是否可以通过它的索引号来选择它,像这样:

browser.input_elements[1] = "whatever"

在这种情况下,Mechanize 中是否存在包含输入元素和值的列表或序列,以便我可以编辑它们?

【问题讨论】:

    标签: python forms mechanize


    【解决方案1】:

    在这里找到了可能有用的东西:

    http://stockrt.github.com/p/emulating-a-browser-in-python-with-mechanize/

    # Select the first (index zero) form
    br.select_form(nr=0)
    

    【讨论】:

      猜你喜欢
      • 2011-02-04
      • 2011-12-02
      • 2015-07-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-06-04
      • 2012-10-22
      • 1970-01-01
      相关资源
      最近更新 更多