Delgan
Delgan

Reputation: 19617

Basic file uploading via website form using POST Requests in Python

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?

Upvotes: 1

Views: 16104

Answers (1)

Martijn Pieters
Martijn Pieters

Reputation: 1121486

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.

Upvotes: 4

Related Questions