当前位置 : 主页 > 编程语言 > python >

Python-随请求发送data/headers

来源:互联网 收集:自由互联 发布时间:2022-06-15
version:2.7.12 #coding=utf-8 import urllib import urllib2 #url = 'http://www.baidu.com' url = 'https://hao.360.cn/?wd_xp1' values = {'name' : 'WHY', 'location' : 'SDU', 'language' : 'Python' } send_headers = {#'Host':'http://www.baidu.com

version:2.7.12

#coding=utf-8
import urllib
import urllib2

#url = 'http://www.baidu.com'
url = 'https://hao.360.cn/?wd_xp1'

values = {'name' : 'WHY',
'location' : 'SDU',
'language' : 'Python' }

send_headers = {#'Host':'http://www.baidu.com',
#'Host':'https://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) # 发送请求同时传【headers】【post】
#req = urllib2.Request(url+'?'+dataHeaders) # 发送请求同时传【headers】【get】

#req = urllib2.Request(url+'?'+data) # 发送请求同时传【data】【get方式】
#req = urllib2.Request(url,data) # 发送请求同时传【data】【post方式】【百度不可用,360可用】

req = urllib2.Request(url,data,send_headers) # 发送请求同时传【data+headers】【post方式】

response = urllib2.urlopen(req) #接受反馈的信息

print response.info()#打印头部信息
print "\"real path\" :",response.geturl()
the_page = response.read() #读取反馈的内容
print the_page.decode('UTF8')


网友评论