我需要 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 中是否有包含输入元素和值的列表或序列,以便我可以编辑它们?
请您参考如下方法:
在这里找到了可能有用的东西:
http://stockrt.github.com/p/emulating-a-browser-in-python-with-mechanize/
# Select the first (index zero) form
br.select_form(nr=0)
