【问题标题】:Sending POST parameters with Python using Mechanize使用 Mechanize 使用 Python 发送 POST 参数
【发布时间】:2012-07-01 20:25:59
【问题描述】:

我想用 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 执行此操作时,会如下所示:

    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 表单中的输入不是一种选择。

提前致谢。

【问题讨论】:

  • 您确实意识到拥有两个具有相同 id 的元素是 非法 HTML?

标签: python post upload mechanize ambiguity


【解决方案1】:

您应该改用find_control;如果有歧义,您可以添加nr 关键字来选择特定控件。在您的情况下,nametype 关键字应该可以。

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

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

请参阅documentation on forms in mechanize

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-02-02
    • 2019-10-25
    • 2019-04-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-11-25
    • 2015-11-04
    相关资源
    最近更新 更多