requests库的使用
1.requests库的安装
pip install requests
2.发送get/post请求
#coding:utf-8 import requests r = requests.get('https://api.github.com/events') #响应状态码 print(r) #<Response [200]> #响应内容 print(r.text) r1 = requests.post('http://httpbin.org/post', data = {'key':'value'}) #响应状态码 print(r1) #响应内容 print(r1.text)
3.发送put/delete/head/options请求
#coding:utf-8 import requests r1 = requests.put('http://httpbin.org/put', data = {'key':'value'}) r2 = requests.delete('http://httpbin.org/delete') r3 = requests.head('http://httpbin.org/get') r4 = requests.options('http://httpbin.org/delete') print(r1,r2,r3,r4) #<Response [200]> <Response [200]> <Response [200]> <Response [200]>
4.发送带参数的URL
#coding:utf-8 import requests payload = {'name': 'zhangsan', 'age': '24'} res = requests.get("http://httpbin.org/get", params=payload) print(res.url) #http://httpbin.org/get?name=zhangsan&age=24
#coding:utf-8 import requests
#传入多个值 payload = {'name': 'zhangsan', 'age': ['24','55']} res = requests.get("http://httpbin.org/get", params=payload) print(res.url) #http://httpbin.org/get?name=zhangsan&age=24&age=55
注意字典里值为 None
的键都不会被添加到 URL 的查询字符串里
5.返回值及相关内容
#coding:utf-8 import requests payload = {'name': 'zhangsan', 'age': ['24','55']} r = requests.get("http://httpbin.org/get", params=payload) print(r.url) #http://httpbin.org/get?name=zhangsan&age=24&age=55 print(r.text) #查看返回内容、是字符串 print(r.status_code) #查看状态码 print(r.json) #返回json格式,但可能会抛出异常 print(r.content)#查看内容,返回的是字节流 print(r.encoding)#查看编码格式
print(r.headers)#响应头
print(r.cookies['cookie_name'])#cookie信息
print(r.history)#追踪重定向
6.请求头
#coding:utf-8 import requests url = 'https://api.github.com/some/endpoint' headers = {'user-agent': 'my-app/0.0.1'} r = requests.get(url, headers=headers)
7.文件
#coding:utf-8 import requests url = 'http://httpbin.org/post' files = {'file': open('report.xls', 'rb')} r = requests.post(url, files=files)
8.cookie
#coding:utf-8 import requests url = 'http://httpbin.org/cookies' cookies = dict(cookies_are='working') r = requests.get(url, cookies=cookies)
9.超时时间
r = requests.get(url, timeout=0.1)
10.