Sending POST parameters with Python using Mechanize

爱⌒轻易说出口 提交于 2019-12-24 07:54:22

问题


I want to fill out this form using Python:

    <form method="post" enctype="multipart/form-data" id="uploadimage">
  <input type="file" name="image" id="image" />
  <input type="submit" name="button" id="button" value="Upload File" class="inputbuttons" />
  <input name="newimage" type="hidden" id="image" value="1" />
  <input name="path" type="hidden" id="imagepath" value="/var/www/httpdocs/images/" />
</form>

As you can see, there are two Parameters that are named exactly the same, so when I'm using Mechanize to do it, what would look like this:

    import mechanize
    br = mechanize.Browser()
    br.open('www.site.tld/upload.php')
    br.select_form(nr=0)

    br.form['image'] = '/home/user/Desktop/image.jpg'
    br.submit()

I am getting the Error:

mechanize._form.AmbiguityError: more than one control matching name 'image'

Every solution I found in the Internet (including this site) didn't work. Is there a different approach? Renaming the input in the HTML form is sadly not an option.

Thanks in Advance.


回答1:


You should use find_control instead; you can add a nr keyword to select a specific control if there is ambiguity. In your case, the name and type keywords should do.

Also note that a file control doesn't take a value; use add_file instead and pass in an open file object:

br.form.find_control(name='image', type='file').add_file(
    open('/home/user/Desktop/image.jpg', 'rb'), 'image/jpg', 'image.jpg')

See the documentation on forms in mechanize.



来源:https://stackoverflow.com/questions/11276461/sending-post-parameters-with-python-using-mechanize

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