Python Mechanize 模块,选择表单中的所有输入字段
我需要 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 中是否存在包含输入元素和值的列表或序列,以便我可以编辑它们?
I need Mechanize to put a certain string into every edittable input field within a selected from. Here is some HTML code as an example:
<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>
Since my Python script would be very tedious to re-write on every website, and would become very website dependent, I want it to select all edittable input fields (while not editting hidden or disabled fields) within a selected form and set the value of each input field to a certain string. However, I will not know the names of each input element. So is there a way in which I can select an input element by its index number? My code looks something like this so far:
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
And at that point, I would want to do something like this: figure out how many editable input elements exist, and select each one by its index number setting it to a value. So can
this be done? I just need an automated way of selecting input fields and setting them to a value without knowing their name or id. Is it possible to select it by its index number, like something like this:
browser.input_elements[1] = "whatever"
In which case is there a list or sequence in Mechanize containing the input elements and values, so I can edit them?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
在这里找到了可能有用的东西:
http:// /stockrt.github.com/p/emulated-a-browser-in-python-with-mechanize/
Found something that might be of use here:
http://stockrt.github.com/p/emulating-a-browser-in-python-with-mechanize/