Python如何根据请求动态设置data和headers?
- 内容介绍
- 文章标签
- 相关推荐
本文共计238个文字,预计阅读时间需要1分钟。
版本:2.7.12
version:2.7.12
import urllib
import urllib2
#url = 'www.baidu.com'
url = 'hao.360.cn/?wd_xp1'
values = {'name' : 'WHY',
'location' : 'SDU',
'language' : 'Python' }
send_headers = {#'Host':'www.baidu.com',
#'Host':'hao.360.cn/?wd_xp1',
'User-Agent':'Mozilla/5.0 (Windows NT 6.2; rv:16.0) Gecko/20100101 Firefox/16.0',
'Accept':'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
'Connection':'keep-alive'}
data = urllib.urlencode(values,'utf8') # 编码工作
dataHeaders = urllib.urlencode(send_headers,'utf8')
#req = urllib2.Request(url)
#req = urllib2.Request(url = url,headers = send_headers) # 发送请求同时传
#req = urllib2.Request(url+'?'+dataHeaders) # 发送请求同时传
#req = urllib2.Request(url+'?'+data) # 发送请求同时传
#req = urllib2.Request(url,data) # 发送请求同时传
req = urllib2.Request(url,data,send_headers) # 发送请求同时传
response = urllib2.urlopen(req) #接受反馈的信息
print response.info()#打印头部信息
print "\"real path\" :",response.geturl()
the_page = response.read() #读取反馈的内容
print the_page.decode('UTF8')
本文共计238个文字,预计阅读时间需要1分钟。
版本:2.7.12
version:2.7.12
import urllib
import urllib2
#url = 'www.baidu.com'
url = 'hao.360.cn/?wd_xp1'
values = {'name' : 'WHY',
'location' : 'SDU',
'language' : 'Python' }
send_headers = {#'Host':'www.baidu.com',
#'Host':'hao.360.cn/?wd_xp1',
'User-Agent':'Mozilla/5.0 (Windows NT 6.2; rv:16.0) Gecko/20100101 Firefox/16.0',
'Accept':'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
'Connection':'keep-alive'}
data = urllib.urlencode(values,'utf8') # 编码工作
dataHeaders = urllib.urlencode(send_headers,'utf8')
#req = urllib2.Request(url)
#req = urllib2.Request(url = url,headers = send_headers) # 发送请求同时传
#req = urllib2.Request(url+'?'+dataHeaders) # 发送请求同时传
#req = urllib2.Request(url+'?'+data) # 发送请求同时传
#req = urllib2.Request(url,data) # 发送请求同时传
req = urllib2.Request(url,data,send_headers) # 发送请求同时传
response = urllib2.urlopen(req) #接受反馈的信息
print response.info()#打印头部信息
print "\"real path\" :",response.geturl()
the_page = response.read() #读取反馈的内容
print the_page.decode('UTF8')

