Python中原生的一款基于网络请求的模块。
作用:模拟浏览器发请求
安装pip install 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')
传递参数
payload = {'key1': 'value1', 'key2': 'value2'}
r = requests.get("http://httpbin.org/get", params=payload)
# 还可以将一个列表作为值传入:
payload = {'key1': 'value1', 'key2': ['value2', 'value3']}
响应内容
# Requests 会自动解码来自服务器的内容。大多数 unicode 字符集都能被无缝地解码。
r = requests.get('https://api.github.com/events')
r.text
# 查看编码
r.encoding
# 改变编码
r.encoding = 'ISO-8859-1'
## 二进制响应内容(以字节的方式访问请求响应体)
r.content
## json响应内容(内置的 JSON 解码器)
r.json()
定制请求头
# 简单地传递一个 dict 给 headers 参数就可以了。
url = 'https://api.github.com/some/endpoint'
headers = {'user-agent': 'my-app/0.0.1'}
r = requests.get(url, headers=headers)
注意: 定制 header 的优先级低于某些特定的信息源,例如:
- 如果在 .netrc 中设置了用户认证信息,使用 headers= 设置的授权就不会生效。而如果设置了 auth= 参数,.netrc 的设置就无效了。
- 如果被重定向到别的主机,授权 header 就会被删除。
- 代理授权 header 会被 URL 中提供的代理身份覆盖掉。
- 在我们能判断内容长度的情况下,header 的 Content-Length 会被改写。
你想要发送一些编码为表单形式的数据,只需简单地传递一个字典给 data 参数。你的数据字典在发出请求时会自动编码为表单形式:
payload = {'key1': 'value1', 'key2': 'value2'}
r = requests.post("http://httpbin.org/post", data=payload)
# 你还可以为 data 参数传入一个元组列表:
payload = (('key1', 'value1'), ('key1', 'value2'))
# 发送 json 的 POST/PATCH 数据:
url = 'https://api.github.com/some/endpoint'
payload = {'some': 'data'}
requests.post(url, data=json.dumps(payload)) # 2.4.2 版:requests.post(url, json=payload)
上传 Multipart-Encoded 的文件
url = 'http://httpbin.org/post'
files = {'file': open('report.xls', 'rb')}
r = requests.post(url, files=files)
# 可以显式地设置文件名,文件类型和请求头:
files = {'file': ('report.xls', open('report.xls', 'rb'), 'application/vnd.ms-excel', {'Expires': '0'})}
状态响应码
r = requests.get('http://httpbin.org/get')
r.status_code
# 内置的状态码查询对象
r.status_code == requests.codes.ok
# 抛出错误请求异常
r.raise_for_status()
响应头
r.headers # 查看响应头
## 查看响应头特定字段
r.headers['Content-Type']
r.headers.get('content-type')
Cookies
r.cookies['example_cookie_name']
# 发送cookies
url = 'http://httpbin.org/cookies'
cookies = dict(cookies_are='working')
r = requests.get(url, cookies=cookies)
# Cookie 的返回对象为 RequestsCookieJar,它的行为和字典类似,但接口更为完整,适合跨域名跨路径使用。你还可以把 Cookie Jar 传到 Requests 中:
jar = requests.cookies.RequestsCookieJar()
jar.set('tasty_cookie', 'yum', domain='httpbin.org', path='/cookies')
jar.set('gross_cookie', 'blech', domain='httpbin.org', path='/elsewhere')
url = 'http://httpbin.org/cookies'
r = requests.get(url, cookies=jar)
r.text -> '{"cookies": {"tasty_cookie": "yum"}}'
高级进阶
会话对象(Session)
会话对象让你能够跨请求保持某些参数。
s = requests.Session()
s.get('http://httpbin.org/cookies/set/sessioncookie/123456789')
r = s.get("http://httpbin.org/cookies")
print(r.text)
# '{"cookies": {"sessioncookie": "123456789"}}'
会话也可用来为请求方法提供缺省数据。这是通过为会话对象的属性提供数据来实现的:
s = requests.Session()
s.auth = ('user', 'pass')
s.headers.update({'x-test': 'true'})
# both 'x-test' and 'x-test2' are sent
s.get('http://httpbin.org/headers', headers={'x-test2': 'true'})
流式上传
# 仅需为你的请求体提供一个类文件对象即可:
with open('massive-body') as f:
requests.post('http://some.url/streamed', data=f)
响应体内容工作流
# 默认情况下,当你进行网络请求后,响应体会立即被下载。你可以通过 stream 参数,推迟下载响应体,直到访问 Response.content 属性再去下载: r = requests.get(tarball_url, stream=True) 你可以进一步使用 Response.iter_content 和 Response.iter_lines 方法来控制工作流,或者以 Response.raw 从底层 urllib3 的 urllib3.HTTPResponse事件挂钩 # 你可以通过传递一个 {hook_name: callback_function} 字典给 hooks 请求参数为每个请求分配一个钩子函数: hooks=dict(response=callback_function) callback_function 会接受一个数据块作为它的第一个参数。 def callback_function(r, *args, **kwargs): print(r.url)超时(timeout)requests 默认是不会自动进行超时处理的。
# 这一 timeout 值将会用作 connect 和 read 二者的 timeout。 r = requests.get('https://github.com', timeout=5) # 如果要分别制定,就传入一个元组: r = requests.get('https://github.com', timeout=(3.05, 27))设置代理import requests proxies = { "http": "http://10.10.1.10:3128", "https": "http://10.10.1.10:1080", } requests.get("http://example.org", proxies=proxies) # 你也可以通过环境变量 HTTP_PROXY 和 HTTPS_PROXY 来配置代理。 $ export HTTP_PROXY="http://10.10.1.10:3128" $ export HTTPS_PROXY="http://10.10.1.10:1080" # 若你的代理需要使用HTTP Basic Auth,可以使用 http://user:password@host/ 语法: proxies = { "http": "http://user:pass@10.10.1.10:3128/", } # 要为某个特定的连接方式或者主机设置代理,使用 scheme://hostname 作为 key, 它会针对指定的主机和连接方式进行匹配。 proxies = {'http://10.20.1.128': 'http://10.10.1.10:5323'}



