使用Mechanize使用Python发送POST参数 [英] Sending POST parameters with Python using Mechanize

查看:94
本文介绍了使用Mechanize使用Python发送POST参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用Python填写此表单:

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>

如您所见,有两个名称完全相同的参数,因此,当我使用Mechanize进行操作时,将如下所示:

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()

我收到错误消息:

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

我在Internet(包括此站点)上找到的所有解决方案均无效.有其他方法吗? 遗憾的是,无法重命名HTML表单中的输入.

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.

预先感谢.

推荐答案

您应该改用find_control;如果存在歧义,可以添加nr关键字以选择特定的控件.对于您来说,nametype关键字应该可以.

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.

还请注意,文件控件不使用value;改用add_file并传入一个打开的文件对象:

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')

请参见有关机械化表单的文档.

这篇关于使用Mechanize使用Python发送POST参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆