unable to send data using urllib and urllib2 (python)

吃可爱长大的小学妹 提交于 2020-01-03 02:01:04

问题


Hello everybody (first post here).

I am trying to send data to a webpage. This webpage request two fields (a file and an e-mail address) if everything is ok the webpage returns a page saying "everything is ok" and sends a file to the provided e-mail address. I execute the code below and I get nothing in my e-mail account.

import urllib, urllib2

params = urllib.urlencode({'uploaded': open('file'),'email': 'user@domain.com'})
req = urllib2.urlopen('http://webpage.com', params)
print req.read()

the print command gives me the code of the home page (I assume instead it should give the code of the "everything is ok" page).

I think (based o google search) the poster module should do the trick but I need to keep dependencies to a minimum, hence I would like a solution using standard libraries (if that is possible).

Thanks in advance.


回答1:


Thanks everybody for your answers. I solve my problem using the mechanize library.

import mechanize 

br = mechanize.Browser()
br.open('webpage.com') 

email='user@domain.com'

br.select_form(nr=0) 
br['email'] = email 
br.form.add_file(open('filename'), 'mime-type', 'filename')    
br.form.set_all_readonly(False) 
br.submit() 



回答2:


This site could checks Referer, User-Agent and Cookies.

Way to handle all of this is using urllib2.OpenerDirector which you can get by urllib2.build_opener.

# Cookies handle
cj = cookielib.CookieJar()
CookieProcessor = urllib2.HTTPCookieProcessor(cj)
# Build OpenerDirector
opener = urllib2.build_opener(CookieProcessor)
# Valid User-Agent from Firefox 3.6.8 on Ubuntu 10.04
user_agent = 'Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.2.8) Gecko/20100723 Ubuntu/10.04 (lucid) Firefox/3.6.8'
# Referer says that you send request from web-site title page
referer = 'http://webpage.com'
opener.addheaders = [
    ('User-Agent', user_agent),
    ('Referer', referer),
    ('Accept-Charset', 'utf-8')
]

Then prepare parameters with urlencode and send request by opener.open(params)

Documentation for Python 2.7: cookielib, OpenerDirector




回答3:


Try this: Using MultipartPostHandler to POST form-data with Python



来源:https://stackoverflow.com/questions/6479539/unable-to-send-data-using-urllib-and-urllib2-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!