码迷,mamicode.com
首页 > 编程语言 > 详细

python urllib2使用心得

时间:2016-03-31 16:54:52      阅读:215      评论:0      收藏:0      [点我收藏+]

标签:

python urllib2使用心得

 

1、http GET请求

过程:获取返回结果,关闭连接,打印结果

f = urllib2.urlopen(req, timeout=10)

the_page = f.read()

f.close()
print the_page

 

2、http GET请求 + 包头

paras = "Token=1234567890;Uuid=0987654321"

send_headers = {"Cookie": paras, "User-Agent": "mixh5monitor", "Content-Type": "application/json"}

req = urllib2.Request(url, headers=send_headers)  # 包头
f = urllib2.urlopen(req, timeout=10)  # 包体

the_page = f.read()

f.close()
print the_page

 

3、http GET请求 + 包头,处理返回响应包头

paras = "Token=1234567890;Uuid=0987654321"

send_headers = {"Cookie": paras, "User-Agent": "mixh5monitor", "Content-Type": "application/json"}

req = urllib2.Request(url, headers=send_headers)  # 包头
f = urllib2.urlopen(req, timeout=10)  # 包体

response_head = f.info().getheader("Content-Type")  # 获取返回包头中Content-Type内容

print response_head

f.close()
技术分享

 

4、http POST请求

postdata = urllib.urlencode({"username": "test", "password": "123456", "type": "Z"})

f = opener.open(url, postdata, timeout=10)

the_page = f.read()

f.close()
print the_page

 

5、http POST请求 + 包头

postdata = urllib.urlencode({"username": "test", "password": "123456", "type": "Z"})

paras = "Token=1234567890;Uuid=0987654321"

send_headers = {"Cookie": paras, "User-Agent": "mixh5monitor", "Content-Type": "application/json"}

req = urllib2.Request(url, headers=send_headers)  # 包头
f = opener.open(req, postdata, timeout=10)
the_page = f.read()
f.close()
print the_page

 

 

6、http POST请求 + 包头,处理返回响应包头

postdata = urllib.urlencode({"username": "test", "password": "123456", "type": "Z"})

paras = "Token=1234567890;Uuid=0987654321"

send_headers = {"Cookie": paras, "User-Agent": "mixh5monitor", "Content-Type": "application/json"}

req = urllib2.Request(url, headers=send_headers)  # 包头
f = opener.open(req, postdata, timeout=10)

response_head = f.info().getheader("Cookie")  # 获取返回包头中Cookie内容

print response_head
f.close()

http包头、包体的学习参考: http://www.cnblogs.com/shhnwangjian/p/5110304.html

python urllib2使用心得

标签:

原文地址:http://www.cnblogs.com/shhnwangjian/p/5341483.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!