I want to fill some web-form with python script and send with POST-request. The problem is that form has fileuploading. I found this: poster for python. So, I came with FireBug at website with form and filled it. What I saw:
values[action] add_save
values[mod] blog
values[depth] 2
values[pid] 121
values[title] title
values[title_eng] title_en
img PNG...[a lot of binary image data]
That site uses authorization, so I have:
passman = urllib2.HTTPPasswordMgrWithDefaultRealm()
passman.add_password(None, theurl, username, password)
authhandler = urllib2.HTTPBasicAuthHandler(passman)
opener = poster.streaminghttp.register_openers()
opener.add_handler(authhandler)
Now I came with default sample from website and wrote the code:
index = """some parsed integer"""
datagen, headers = multipart_encode({
'values[action]': 'add_save',
'values[mod]': 'blog',
'values[depth]': '2',
'values[pid]': index,
'values[title]' : 'title',
'values[title_eng]' : 'title_eng',
'img': open('1.png', 'rb')
})
request = urllib2.Request(theurl, datagen, headers)
getdata = urllib2.urlopen(request)
print getdata.read()
I don't have errors, etc. But after sending POST the script doesn't add it into database (when I do that by hands everything is fine).
I added this code:
for value in datagen:
print value
And the result is: link. (123 number in text is that index variabl开发者_开发知识库e value).
I haven't used your approach before, but have successfully used MultipartPostHandler to do something similar. Abbreviated, an example would look like the following.
import MultipartPostHandler
import urllib2
form_opener = urllib2.build_opener(MultipartPostHandler.MultipartPostHandler)
urllib2.install_opener(form_opener)
datagen = {vars}
o=opener.open(url, datagen)
MultipartPostHandler can be found here.
You can also add urllib2.HTTPCookieProcessor() to the opener to handle authentication like this:
import urllib
opener = urllib2.build_opener(urllib2.HTTPCookieProcessor())
# Or, (MultipartPostHandler.MultipartPostHandler, urllib2.HTTPCookieProcessor())
urllib2.install_opener(opener)
login = urllib.urlencode(dict(username='user',password='pass',login='Login'))
o=opener.open(url, login)
This is my first post so forgive me if I'm a little off target :)
Have you checked the response of each of the requests you made(including logging in to the site) to make sure you have been served the correct page and have the correct cookie set?
精彩评论