您的位置:首页 > 理论基础 > 计算机网络

初识网络爬虫之二:httplib与urllib实现

2017-10-20 22:13 288 查看
#coding:utf8

#GET请求
import httplib
conn = None
try:
conn = httplib.HTTPConnection("www.baidu.com")
conn.request("GET", "/")
response = conn.getresponse()
print response.status, response.reason
print '-' * 40
headers = response.getheaders()
for h in headers:
print h
print '-' * 40
print response.msg
except Exception,e:
print e
finally:
if conn:
conn.close()

#POST请求
import httplib, urllib
conn = None
try:
params = urllib.urlencode({'name': 'qiye', 'age':22})
headers = {"Content-type": "application/x-www-form-urlencoded"
, "Accept": "text/plain"}
conn = httplib.HTTPConnection("www.baidu.com", 80, timeout=3)
conn.request("POST", "/login", params, headers)
response = conn.getresponse()
print response.getheaders() #获取头信
4000
息
print response.status
print response.read()
except Exception, e:
print e
finally:
if conn:
conn.close()
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: