requestsAPI
之前就有在用过requests 模块,在使用scrayp框架爬虫之前。但是一直都没有记录,借于这几天刚好用requests在工作上做promotion自动化,算是比较了解requests 模块了,顺便做个requestsAPI 的记录。
1.pip install request (安装)
2.http://docs.python-requests.org/zh_CN/latest/user/quickstart.html (官网)
3.ret = requests.post('http://httpbin.org/post', data = {'key':'value'}) post 请求
4.ret = requests.get("http://httpbin.org/get", params=params) get请求的带参数方式
5.ret = requests.post('http://httpbin.org/post', cookies=cookies, headers=headers, data = {'key':'value'})
6.post上传文件
files = {'file': ('report.xls', open('report.xls', 'rb'), 'application/vnd.ms-excel', {'Expires': '0'})}
ret = requests.post(url, files=files)
7.响应内容
r.text #Requests 会自动解码来自服务器的内容Unicode。 r.content #以字节的方式访问请求响应体,对于非文本请求 r.encoding #查看当前编码方式 r.encoding = 'ISO-8859-1' #设置编码方式 r.json() #如果返回值是json格式,可以自动转换为json数据 r.status_code #获取返回状态码 r.headers #获取响应头内容 r.cookies.get_dict() #获取cookies值,字典类型 r.request.headers #获取请求头内容8.请求参数
url = ulr #请求的URL data = {'key':'value'} #非get请求时的请求数据 params = params #get请求的一种带参数形式 cookies = cookies #设置cookies值 headers = headers #设置请求头 files = files #上传文件 allow_redirects = False #请求非HEAD时,禁止重定向 timeout = 0.001 #设置超时时间,(秒) verify=False #忽略SSL证书 verify='/path/to/certfile' #本地证书文件路径 stream=True #文件过大时,需要使用到流式获取 proxies=proxies #设置代理9.requests.Session 可以自动记录headers 和 cookies,再次访问其他url时不需要在传headers 和 cookies,可以简化操作,并且对于登入的重定向非常好用,不在需要禁止重定向来获取cookies。
s = requests.Session() #手动添加cookies with requests.Session() as s: s.get('http://httpbin.org/cookies/set/sessioncookie/123456789')10.如果你在请求中把 stream 设为 True,Requests 无法将连接释放回连接池,除非你 消耗了所有的数据,或者调用了 Response.close。 这样会带来连接效率低下的问题。如果你发现你在使用 stream=True 的同时还在部分读取请求的 body(或者完全没有读取 body),那么你就应该考虑使用 with 语句发送请求,这样可以保证请求一定会被关闭:
with requests.get('http://httpbin.org/get', stream=True) as r:

评论