unable to send data using urllib and urllib2 (python)

送分小仙女□ 提交于 2019-12-06 15:42:54

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() 

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

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