1

I try to upload a file on a random website using Python and HTTP requests. For this, I use the handy library named Requests.

According to the documentation, and some answers on StackOverflow here and there, I just have to add a files parameter in my application, after studying the DOM of the web page.

The method is simple:

  1. Look in the source code for the URL of the form ("action" attribute);
  2. Look in the source code for the "name" attribute of the uploading button ;
  3. Look in the source code for the "name" and "value" attributes of the submit form button ;
  4. Complete the Python code with the required parameters.

Sometimes this works fine. Indeed, I managed to upload a file on this site : http://pastebin.ca/upload.php

After looking in the source code, the URL of the form is upload.php, the buttons names are file and s, the value is Upload, so I get the following code:

url = "http://pastebin.ca/upload.php"
myFile = open("text.txt","rb")
r = requests.get(url,data={'s':'Upload'},files={'file':myFile})
print r.text.find("The uploaded file has been accepted.") 
# ≠ -1

But now, let's look at that site: http://www.pictureshack.us/

The corresponding code is as follows:

url = "http://www.pictureshack.us/index2.php"
myFile = open("text.txt","rb")
r = requests.get(url,data={'Upload':'upload picture'},files={'userfile':myFile})
print r.text.find("Unsupported File Type!") 
# = -1

In fact, the only difference I see between these two sites is that for the first, the URL where the work is done when submitting the form is the same as the page where the form is and where the files are uploaded.

But that does not solve my problem, because I still do not know how to submit my file in the second case.

I tried to make my request on the main page instead of the .php, but of course it does not work.


In addition, I have another question.

Suppose that some form elements do not have "name" attribute. How am I supposed to designate it at my request with Python?

For example, this site: http://imagesup.org/

The submitting form button looks like this: <input type="submit" value="Héberger !">

How can I use it in my data parameters?

Community
  • 1
  • 1
Delgan
  • 18,571
  • 11
  • 90
  • 141
  • 1
    You can safely ignore `input` elements without a `name` attribute; these are not sent to the server at all. The `submit` button on `imagesup.org` can be ignored entirely. – Martijn Pieters May 17 '14 at 14:40

1 Answers1

4

The forms have another component you must honour: the method attribute. You are using GET requests, but the forms you are referring to use method="post". Use requests.post to send a POST request.

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
  • Well, I'm just stupid... I said in my title that I uses POST Requests, I KNEW that I should use POST Requests in order to upload file. And yet, I did not even notice my mistake while she was under my eyes... Thank you. – Delgan May 17 '14 at 14:49