Take the 2-minute tour ×

I am a newbie to web development, so please be mercy if the following question sounds a bit naive. How can I post to a web form using python? I know the web form is something like this, and I want to upload a local file for it to be processed online and get the returned data

<form action="process.php" method="post" enctype="multipart/form-data">
    <input type="file" name="file" id="file" id="chooser" /><br />

Here's what I have for my python program so far.

upfile = urllib.urlencode( {'file':path/to/my/local/file})
filehandle = urllib.urlopen('http://www.comdroid.org/', upfile)
soup = BeautifulSoup(filehandle)
print soup

I want to see the returned results, but the current code snippet only gives me the result without processing my uploaded file. Is there anything I am missing


import urllib2
import urllib 
import requests
import os
files1 ={'file':open('/opt/apps/au.com.psyborg.sbc-5.apk','rb')‌​}
#response= os.system("curl --form   file=@/opt/apps/au.com.psyborg.sbc-5.apk --form submit=Upload www.comdroid.org/process.php")
req = requests.post('comdroid.org/process.php', files = files1) 
print req.text

The weird thing is I cannot do it with request, the server complains my file is not .apk file, which it actually is. But if I switch to curl using os.system as commented out, it works! So I doubt I am missing something here in request. Any suggestion?

share|improve this question
add comment

1 Answer

If you look at the form's action property, it's going to process.php - so you'll need to send your file upload to http://www.comdroid.org/process.php.

Doing file uploads with the standard library is a bit of a pain - if you're allowed to, I would recommend using requests for this - they even have an example of what you're asking for in their documentation:

url = 'http://httpbin.org/post'
files = {'file': open('report.xls', 'rb')}
r = requests.post(url, files=files)

I also found this SO answer on how to do it with the mechanize library, and a code sample that might help if you want to do it with the standard library.

share|improve this answer
thanks, I understand the whole frame now,but was still not able to get the result desired. What happened is that the server keeps rejecting my request by saying that my file is not required .apk file.(which it actually is. –  Daniel Mar 9 '13 at 17:17
please see my update –  Daniel Mar 9 '13 at 17:26
Is it possible that the way "request" encoded the .apk file somehow twisted it and the .apk file cannot be recognized by the server? –  Daniel Mar 9 '13 at 17:27
No, requests shouldn't do anything to alter the contents of your file - either the detection logic on the form you're uploading to is wrong, or the file you're trying to upload is not an apk. What is the actual error message? –  girasquid Mar 9 '13 at 17:47
show 1 more comment

Your Answer


