requests 教程 NOT FINISHED
通过requests模块与API进行交互
思考题
- 如何在程序中引入 requests 模块?
import requests
- 如何使用 requests 模块发送请求?
- POST 和 GET 是什么意思?如何用 requests 模块发送 POST 或者 GET 请求?
Install
pip install requests
顺利安装
Stay updated
虽然本次package是刚刚下载的,顺便检索了意下如何更新 pip install requests --upgrade
基本功能
HTTP requests
GET, POST, PUT, DELETE, HEAD, OPTIONS
import requests
r = requests.get('https://api.github.com/events')
r = requests.post('http://httpbin.org/post', data = {'key':'value'})
r = requests.put('http://httpbin.org/put', data = {'key':'value'})
r = requests.delete('http://httpbin.org/delete')
r = requests.head('http://httpbin.org/get')
r = requests.options('http://httpbin.org/get')
在URL中传参 Passing Parameters in URLs
手动在URL中添加参数较麻烦,通过requests模块,以字典的格式传入参数值即可。
payload = {'key1':'value1', 'key2':'value2'}
r = requests.get('http://httpbin.org/get', params=payload))
通过r.url
来查看参数是否正常加入到URL中
也可以将多个值作为列表传入
payload = {'key1': 'value1', 'key2': ['value2', 'value3']}
r = requests.get('http://httpbin.org/get', params=payload)
print(r.url)
http://httpbin.org/get?key1=value1&key2=value2&key2=value3
My question: key2=valu2&key2=value3 为什么一个参数会有两个不同的值?
Response Content 返回内容
r.text
requests模块根据header的内容,将内容自动解码。可以通过r.encode
察看解码方式,或者更改解码方式。
JSON Response Content
r.json()
注意返回json并不意味着成功返回。查看请求是否成功,使用
r.raise_for_status
或者 r.status_code
Raw Response Content
如果需要获得raw data, 请求时设定stream=True
r = requests.get('https://api.github.com/events', stream=True)
r.raw
一般情况下,原始数据存入文件,如下述:
with open(filename, 'wb') as fd:
for chunck in r.iter_content(chunck_size=128):
fd.write(chunck)
More Complicated POST requests
将查询的字符串(名称/值对)传入data参数,如下
payload = {'key1': 'value1', 'key2': 'value2'}
r = requests.post("http://httpbin.org/post", data=payload)
print(r.text)
不直接传词典的话,也可以通过json来传参数
import json
url = 'https://api.github.com/some/endpoint'
payload = {'some': 'data'}
r = requests.post(url, data=json.dumps(payload))
或者直接使用json
参数
r = requests.post(url, json=payload)
Response Status Codes
r.status_code
r.raise_for_status()
Response Headers
r.headers
返回的词典是HTTP header专用的,不区分大小写。可以选择大小写的格式:
r.headers['Content-Type']
r.headers.get('content-type')
Cookies
r.cookies['example_cookie_name']
高级功能
Authentication 验证
清晰幽默的教程。