How to upload a file, using Python Mechanize, with a twist :)
Ok I have only been using Mechanize for one day, so be nice :P
I would like complete a form including one (or two if possible) file upload style fields. The ones where you click, and it lets you browse for a file.
(I want to automate the uploading of a .torrent to a private tracker / site)
Now the two issues I have had is on the site none of the forms have names, so I have been using the index of the form to choose them.
br.select_form(nr=4)
Now the problem is I want to also upload a file when I submit the form. There are two file fields and I dont think I am properly specifying each one. Here is a "print" of the form made using "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(nam开发者_C百科e=)>
<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)>>
I tried this code hoping it would just default to the first one:
br.form.add_file(open(filename), 'text/plain', filename)
But, it gives this error
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'
So how do I:
- tell it which file field I meant
- or upload the file a different way
Thank you very much :)
Community: Please fix, I'm a casual passerby who encountered this error and solved it.
br.form.add_file(open(filename), 'text/plain', filename, **kwargs)
You need to resolve the ambiguity by passing in an extra keyword argument to identify the specific control you want to add the file to. You can add name, id, nr or label.
In this case it would be
br.form.add_file(open(filename), 'text/plain', filename, name='file')
精彩评论