1、介绍python
Requests 是用Python语言编写,基于 urllib,可是它比 urllib 更加方便,能够节约咱们大量的工做,彻底知足 HTTP 测试需求。Requests 的哲学是以 PEP 20 的习语为中心开发的,因此它比 urllib 更加 Pythoner。更重要的一点是它支持 Python3 !git
2、用法 github
一、使用 Requests 发送网络请求json
import requests r = requests.get('https://github.com/timeline.json') 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 参数api
payload = {'key1': 'value1', 'key2': 'value2'} r = requests.get("http://httpbin.org/get", params=payload)
经过打印输出该 URL,你能看到 URL 已被正确编码:服务器
print(r.url) http://httpbin.org/get?key2=value2&key1=value1
三、响应内容cookie
r.text能够看到地址响应的内容网络
Requests 会自动解码来自服务器的内容。大多数 unicode 字符集都能被无缝地解码。app
四、二进制响应内容ide
你也能以字节的方式访问请求响应体
r.content
Requests 会自动为你解码 gzip 和 deflate 传输编码的响应数据。
例:以请求返回的二进制数据建立一张图片:
from PIL import Image from io import BytesIO i = Image.open(BytesIO(r.content))
五、JSON 响应内容
Requests 中也有一个内置的 JSON ×××
import requests r = requests.get('https://github.com/timeline.json')
r.json() 若是 JSON 解码失败, r.json() 就会抛出一个异常。例如,响应内容是 401 (Unauthorized),尝试访问r.json() 将会抛出 ValueError: No JSON object could be decoded 异常。
六、定制请求头
url = 'https://api.github.com/some/endpoint' headers = {'user-agent': 'my-app/0.0.1'} r = requests.get(url, headers=headers)
全部的 header 值必须是 string、bytestring 或者 unicode。
七、更加复杂的 POST 请求
payload = (('key1', 'value1'), ('key1', '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))
八、响应状态码
r.status_code(状态码)
r.raise_for_status() (抛出异常)
九、响应头
r.headers
十、Cookie
url = 'http://example.com/some/cookie/setting/url' r = requests.get(url) r.cookies['example_cookie_name'] 'example_cookie_value' 发送你的cookies到服务器:(Cookie 的返回对象为 RequestsCookieJar) r = 'http://httpbin.org/cookies' cookies = dict(cookies_are='working') r = requests.get(url, cookies=cookies) r.text '{"cookies": {"cookies_are": "working"}}'
十一、重定向与请求历史
默认状况下,除了 HEAD, Requests 会自动处理全部重定向。可使用响应对象的 history 方法来追踪重定向。
Response.history 是一个 Response 对象的列表,为了完成请求而建立了这些对象。这个对象列表按照从最老到最近的请求进行排序。
例:Github 将全部的 HTTP 请求重定向到 HTTPS:
r = requests.get('http://github.com') r.url 'https://github.com/' r.status_code 200 r.history [<Response [301]>]
能够经过 allow_redirects 参数禁用重定向处理:
r = requests.get('http://github.com', allow_redirects=False) r.status_code 301 r.history []
十二、超时
你能够告诉 requests在通过以timeout参数设定的秒数时间以后中止等待响应。若是不使用,你的程序可能会永远失去响应:
requests.get('http://github.com', timeout=0.001)
注意:
timeout仅对链接过程有效,与响应体的下载无关。timeout并非整个下载响应的时间限制,而是若是服务器在timeout秒内没有应答,将会引起一个异常。
1三、错误与异常
遇到网络问题(如:DNS 查询失败、拒绝链接等)时,Requests 会抛出一个 ConnectionError 异常。
若是 HTTP 请求返回了不成功的状态码, Response.raise_for_status() 会抛出一个 HTTPError 异常。
若请求超时,则抛出一个 Timeout 异常。
若请求超过了设定的最大重定向次数,则会抛出一个 TooManyRedirects 异常。