How to upload a file using Python Mechanize using a twist :)

Ok, I only used Mechanize for one day, so be nice: P

I would like to fill out a form, including one (or two, if possible) file upload style. The ones you click and allow you to view the file.

(I want to automate uploading .torrent to a private tracker / site)

Now the two problems that I had are on the site, none of the forms have names, so I used the form index to select them.

br.select_form(nr=4)

Now the problem is that I also want to upload the file when I submit the form. There are two file fields, and I do not think I am setting them correctly. Here is the "print" 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(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)>>

I tried this code, hoping that it will be the first by default:

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 am I:

  • ,
  • -.

:)

+3
1

: , , , .

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

, , , . , id, nr .

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

Source: https://habr.com/ru/post/1776639/


All Articles