Python3.4.3 post请求网页数据设置请求头headers

来源:赵克立博客 分类: Python 标签:Python发布时间:2015-11-21 02:41:56最后更新:2015-11-21 03:26:51浏览:12290
版权声明:
本文为博主原创文章,转载请声明原文链接...谢谢。o_0。
更新时间:
2015-11-21 03:26:51
温馨提示:
学无止境,技术类文章有它的时效性,请留意文章更新时间,如发现内容有误请留言指出,防止别人"踩坑",我会及时更新文章
import urllib.request
import urllib.parse
#请求头
headers = { 
	'User-Agent' : "Mozilla/5.0 (Windows NT 10.0; WOW64)",
	'Referer':'http://www.xxxxxx.com/'
		 }
#get取网页数据
def geturl(url,data={}):
	try:
		params=urllib.parse.urlencode(data).encode(encoding='UTF8')
		req=urllib.request.Request("%s?%s"%(url, params))
		#设置headers
		for i in headers:
			req.add_header(i,headers[i])
		
		r=urllib.request.urlopen(req)
		html =r.read()
		return html
	except urllib.error.HTTPError as e:
	    print(e.code)
	    print(e.read().decode("utf8"))
#post取网页数据	
def posturl(url,data={}):
	try:
		params=urllib.parse.urlencode(data).encode(encoding='UTF8')
		req = urllib.request.Request(url, params,headers)
		r = urllib.request.urlopen(req)
		html =r.read()
		return html
	except urllib.error.HTTPError as e:
	    print(e.code)
	    print(e.read().decode("utf8"))



微信号:kelicom QQ群:215861553 紧急求助须知
Win32/PHP/JS/Android/Python