您的位置:首页 > 产品设计 > UI/UE

Requests库使用

2016-04-06 11:50 330 查看
HTTP请求大致有GET、POST、PUT、DELETE、HEAD、OPTIONS六种,对应到requests库上的使用方法依次为

GET

import requests
url = 'http://www.baidu.com'
payload = {'key1': 'value1', 'key2': 'value2'}
headers = {}
r = requests.get(url, params=payload, headers=headers)
print r.text
其中payload为GET携带的数据,附在url后面



POST

#-*- coding:utf-8 -*-
import requests
url1 = 'http://www.exanple.com/login'#登陆地址
url2 = "http://www.example.com/main"#需要登陆才能访问的地址
data={"user":"user","password":"pass"}
headers = { "Accept":"text/html,application/xhtml+xml,application/xml;",
"Accept-Encoding":"gzip",
"Accept-Language":"zh-CN,zh;q=0.8",
"Referer":"http://www.example.com/",
"User-Agent":"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/42.0.2311.90 Safari/537.36"
}
res1 = requests.post(url1, data=data, headers=headers)
res2 = requests.get(url2, cookies=res1.cookies, headers=headers)

print res2.content#获得二进制响应内容
print res2.raw#获得原始响应内容,需要stream=True
print res2.raw.read(50)
print type(res2.text)#返回解码成unicode的内容
print res2.url
print res2.history#追踪重定向
print res2.cookies
print res2.cookies['example_cookie_name']
print res2.headers
print res2.headers['Content-Type']
print res2.headers.get('content-type')
print res2.json#讲返回内容编码为json
print res2.encoding#返回内容编码
print res2.status_code#返回http状态码
print res2.raise_for_status()#返回错误状态码


此处模拟登录方法借用了res1.cookies,实现不同请求之间的状态保持,可以借用session对象简要完成
#-*- coding:utf-8 -*-
import requests
s = requests.Session()
url1 = 'http://www.exanple.com/login'#登陆地址
url2 = "http://www.example.com/main"#需要登陆才能访问的页面地址
data={"user":"user","password":"pass"}
headers = { "Accept":"text/html,application/xhtml+xml,application/xml;",
"Accept-Encoding":"gzip",
"Accept-Language":"zh-CN,zh;q=0.8",
"Referer":"http://www.example.com/",
"User-Agent":"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/42.0.2311.90 Safari/537.36"
}
res1 = s.post(url1, data=data, headers=headers)
res2 = s.get(url2, headers=headers)
print(res2.content)
其他请求使用方式类似,为
>>> r = requests.put("http://httpbin.org/put")
>>> r = requests.delete("http://httpbin.org/delete")
>>> r = requests.head("http://httpbin.org/get")
>>> r = requests.options("http://httpbin.org/get")
除此之外,requests设置代理的方式为
import requests

proxies = {
'http': 'http://10.10.1.10:3128',
'https': 'http://10.10.1.10:1080',
}

requests.get('http://example.org', proxies=proxies)
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: