发送请求

1
2
3
import requests # 导入库
# 尝试获取某个网页
r =requests.get('https://www.baidu.com')

r 是一个response对象,从这个对象可以获取想要的信息。

1
2
3
4
5
r = requests.post('http://httpbin.org/post')
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")

传递参数

当传递参数的时候,若手动构建,那么数据会以键/值对的形式置于 URL 中,跟在一个问号的后面。例如, httpbin.org/get?key=val

Requests 允许你使用 params 关键字参数,以一个字符串字典来提供这些参数。举例来说,如果你想传递 key1=value1key2=value2httpbin.org/get ,那么你可以使用如下代码

1
2
3
4
5
6
7
8
myparam={'key1':'value1','key2':'value2'}
r = requests.get("http://httpbin.org/get", params=myparam)

# 将列表作为值传入
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
打印URL
1
print(r.url)

相应内容

1
2
3
4
5
6
# 读取服务器相应内容
r = requests.get('https://github.com/timeline.json')
r.text
# Requests 会自动解码来自服务器的内容。大多数 unicode 字符集都能被无缝地解码。
# 改变输出编码
r.encoding = 'ISO-8859-1'
二进制相应内容
1
2
3
4
5
6
7
# 非文本请求
r.content
Requests 会自动为你解码 gzip 和 deflate 传输编码的响应数据。
例如,以请求返回的二进制数据创建一张图片,你可以使用如下代码:
from PIL import Image
from io import BytesIO
i = Image.open(BytesIO(r.content))
JSON相应内容

requests内置JSON解码器,帮助处理JSON数据

1
2
3
4
import requests
r = requests.get('https://github.com/timeline.json')
r.json()
# [{u'repository': {u'open_issues': 0, u'url': 'https://github.com/...
原始相应内容
1
2
3
4
5
r = requests.get('https://github.com/timeline.json', stream=True)
r.raw
<requests.packages.urllib3.response.HTTPResponse object at 0x101194810>
r.raw.read(10)
'\x1f\x8b\x08\x00\x00\x00\x00\x00\x00\x03'

定制请求头

如果你想为请求添加 HTTP 头部,只要简单地传递一个 dictheaders 参数就可以了。

例如,在前一个示例中我们没有指定 content-type:

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

更加复杂POST请求

你想要发送一些编码为表单形式的数据——非常像一个 HTML 表单。要实现这个,只需简单地传递一个字典给 data 参数。你的数据字典在发出请求时会自动编码为表单形式

1
2
3
4
5
6
7
8
9
payload = {'key1': 'value1', 'key2': 'value2'}
r = requests.post("http://httpbin.org/post", data=payload)
print(r.text)
{
"form": {
"key2": "value2",
"key1": "value1"
},
}

POST Multipart-Encoded)的文件

1
2
3
4
5
6
7
8
9
10
11
>>> url = 'http://httpbin.org/post'
>>> files = {'file': open('report.xls', 'rb')}
>>> r = requests.post(url, files=files)
>>> r.text
{
...
"files": {
"file": "<censored...binary...data>"
},
...
}

### 状态响应码

1
2
3
4
5
6
7
# 检测相应状态码
r = requests.get('http://httpbin.org/get')
r.status_code
200
# 为方便引用,Requests还附带了一个内置的状态码查询对象:
r.status_code == requests.codes.ok
True

相应头

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
我们可以查看以一个 Python 字典形式展示的服务器响应头:
>>> r.headers
{
'content-encoding': 'gzip',
'transfer-encoding': 'chunked',
'connection': 'close',
'server': 'nginx/1.0.4',
'x-runtime': '148ms',
'etag': '"e1ca502697e5c9317743dc078f67693f"',
'content-type': 'application/json'
}
因此,我们可以使用任意大写形式来访问这些响应头字段:
>>> r.headers['Content-Type']
'application/json'
>>> r.headers.get('content-type')
'application/json'
访问cookie
1
2
3
4
5
# 如果某个响应中包含一些 cookie,你可以快速访问它们:
url = 'http://example.com/some/cookie/setting/url'
r = requests.get(url)
r.cookies['example_cookie_name']
'example_cookie_value'
发送cookie
1
2
3
4
5
6
# 要想发送你的cookies到服务器,可以使用 cookies 参数:
>>> url = 'http://httpbin.org/cookies'
>>> cookies = dict(cookies_are='working')
>>> r = requests.get(url, cookies=cookies)
>>> r.text
'{"cookies": {"cookies_are": "working"}}'