第三方模块 requests 常见应用

1.发送请求

一、http GET 请求

1
2
>>> r = requests.get('https://www.baidu.com',timeout=0.001) #timeout超时设置
# r 为 Response 对象

二、http POST 请求

1
>>> r = requests.post('http://httpbin.org/post', data = {'key':'value'})

三、响应状态码, 响应头查看

1
2
3
4
5
6
7
8
9
10
11
12
13
>>> r = requests.get('http://httpbin.org/get')
>>> r.status_code
200
>>> r.headers
{
'content-encoding': 'gzip',
'transfer-encoding': 'chunked',
'connection': 'close',
'server': 'nginx/1.0.4',
'x-runtime': '148ms',
'etag': '"e1ca502697e5c9317743dc078f67693f"',
'content-type': 'application/json'
}

四、定制请求头

1
2
3
>>> url = 'https://api.github.com/some/endpoint'
>>> headers = {'user-agent': 'my-app/0.0.1'}
>>> r = requests.get(url, headers=headers)

2.传递参数

1
2
3
4
5
# 如请求 url 为 http://httpbin.org/get?key1=value1&key2=value2&key2=value3
>>> 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

3.响应类容

一、文本内容响应

1
2
3
>>> r = requests.get('https://api.github.com/events')
>>> r.text
[{"id":"7433319525","type":"WatchEvent","actor":{"id":6783144......

二、二进制内容响应

Requests 会自动为你解码 gzip 和 deflate 传输编码的响应数据

1
2
3
>>> r = requests.get('https://api.github.com/events')
>>> r.content
[{"id":"7433319525","type":"WatchEvent","actor":{"id":6783144......

三、JSON 内容响应

1
2
3
>>> r = requests.get('https://api.github.com/events')
>>> r.json()
[{"id":"7433369283","type":"CreateEvent","actor":{"id":4654413.....

四、编码解析

Requests 会基于 HTTP 头部对响应的编码作出有根据的推测,你可以查看该编码格式,并且自己可以设置你认为正确的编码。

1
2
3
>>> r.encoding
'utf-8'
>>> r.encoding = 'ISO-8859-1'