问题
I'm logging into a page where they oddly have a form input called login_email
and two form inputs called login_password
. I need to set the value of both but the straightforward call form['login_password']
throws an error:
File "/Library/Python/2.7/site-packages/mechanize/_form.py", line 3101, in find_control
return self._find_control(name, type, kind, id, label, predicate, nr)
File "/Library/Python/2.7/site-packages/mechanize/_form.py", line 3183, in _find_control
raise AmbiguityError("more than one control matching "+description)
mechanize._form.AmbiguityError: more than one control matching name 'login_password'
I just need to find a way to submit form['login_password'] = "Password"
and form['login_password'] = "monkeybutler"
at the same time. I'm not seeing a variable in the Browser
object to change the POST data params.
Any suggestions? Here's what I tried without success:
# Select the first (index zero) form
br.select_form(nr=0)
# Let's search
br.form['login_email'] = 'mommajane@gmail.com'
#my_fields = br.form.fields.select
#my_fields[0].login_password = "Password"
#my_fields[1].login_password = "123qwerty"
br.form['login_password']= ['Password','123qwerty']
br.submit()
回答1:
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.
来源:https://stackoverflow.com/questions/21035713/python-mechanize-handle-two-parameters-with-same-name