如何使用Python Mechanize上传文件,带点小花样 :)

3 投票
1 回答
3568 浏览
提问于 2025-04-16 07:32

好吧,我才刚用Mechanize一天,所以请多包涵 :P

我想要填写一个表单,其中包括一个(或者两个,如果可以的话)文件上传的字段。就是那种你点击后可以浏览文件的。

(我想自动上传一个.torrent文件到一个私人追踪器/网站)

现在我遇到的两个问题是,网站上的表单没有名字,所以我只能用表单的索引来选择它们。

br.select_form(nr=4)

现在的问题是,我想在提交表单的时候也上传一个文件。表单里有两个文件字段,我觉得我没有正确指定每一个。这里是用“print br.form”打印出来的表单内容。

<POST http://www.###.##.##/takeupload.php multipart/form-data
  <HiddenControl(MAX_FILE_SIZE=1000000) (readonly)>
  <TextControl(<None>=http://www.###.##.##:81/announce.php?passkey=###) (readonly)>
  <FileControl(file=<No files added>)>
  <TextControl(name=)>
  <SelectControl(type=[*0, 23, 22, 1, 10, 7, 12, 4, 21, 17, 18, 13, 58, 16, 15, 56, 20, 60, 5, 19, 6, 55, 57, 63, 9])>
  <CheckboxControl(strip=[strip])>
  <FileControl(nfo=<No files added>)>
  <TextareaControl(descr=)>
  <SubmitControl(<None>=Do it!) (readonly)>>

我试了这个代码,希望它能默认选择第一个:

br.form.add_file(open(filename), 'text/plain', filename)

但是,它给了我这个错误。

    Traceback (most recent call last):
  File "script.py", line 53, in <module>
    br.form.add_file(open(filename), 'text/plain', filename)
  File "/usr/local/lib/python2.6/dist-packages/mechanize-0.2.4-py2.6.egg/mechanize/_form.py", line 2968, in add_file
    self.find_control(name, "file", id=id, label=label, nr=nr).add_file(
  File "/usr/local/lib/python2.6/dist-packages/mechanize-0.2.4-py2.6.egg/mechanize/_form.py", line 3101, in find_control
    return self._find_control(name, type, kind, id, label, predicate, nr)
  File "/usr/local/lib/python2.6/dist-packages/mechanize-0.2.4-py2.6.egg/mechanize/_form.py", line 3183, in _find_control
    raise AmbiguityError("more than one control matching "+description)
mechanize._form.AmbiguityError: more than one control matching type 'file'

所以我该怎么做:

  • 告诉它我指的是哪个文件字段
  • 或者用其他方式上传文件

非常感谢你 :)

1 个回答

9

社区:请修复一下,我只是路过的,遇到了这个错误并且解决了它。

br.form.add_file(open(filename), 'text/plain', filename, **kwargs)

你需要通过传入一个额外的关键词参数来消除混淆,这样才能明确你想把文件添加到哪个具体的控件上。你可以添加名称、ID、编号或者标签。

在这种情况下,可以这样做:

br.form.add_file(open(filename), 'text/plain', filename, name='file')

撰写回答