python mechanize handle two parameters with same name

对着背影说爱祢 提交于 2019-12-06 02:41:41

If you are facing two fields with the same name, id and so on, you must use a little workaround, altough its not very clean

First I have defined a simple html file for that example since I did not know the URL you used:

    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
       "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<title>foo</title>
</head>
<body>

<h1>bar</h1>

<form action="input_text.htm">
  <p>name:<br><input name="name" type="text" size="30" maxlength="30"></p>
  <p>sec_name:<br><input name="sec_name" type="text" size="30" maxlength="40"></p>
  <p>sec_name:<br><input name="sec_name" type="text" size="30" maxlength="40"></p>
</form>

</body>
</html>

Afterwards I was able to insert values into those fields quick and dirty by using this python code:

>>> import mechanize
>>> browser = mechanize.Browser()
>>> browser.open("file:///home/foo/index.html")
<response_seek_wrapper at 0x229a7e8 whose wrapped ...
>>> browser.select_form(nr=0)
>>> name = 'foo'
>>> for control in browser.form.controls:
...     if control.name == 'sec_name':
...             control.value = name
...             name = 'bar'
... 
>>> for control in browser.form.controls:
...     print control
... 
<TextControl(name=)>
<TextControl(sec_name=foo)>
<TextControl(sec_name=bar)>
>>> 

It`s not nice but it works. Hope that helped.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!