@songying
2017-12-20T14:58:51.000000Z
字数 2654
阅读 1429
python库
pip install requests
import requests
r = requests.get('url')r = requests.post('url')r = requests.put('url')r = requests.delete("url")r = requests.head("url")r = requests.options("url")
r.text #r.encoding # 响应内容的编码,可以修改r.status_code # 查看响应报文的状态码r.urlr.headers # 查看响应头r.headers['Content-Type']r.headers.get('content-type')
对于非文本请求,例如图片,视频等,你可以以字节的方式访问请求响应内容。
Requests 会自动为你解码
gzip和deflate传输编码的响应数据。
r.content # 以二进制的响应输出内容,适合图片,视频
有时我们请求的是一个JSON文件,这个时候我们需要使用解析文件
r.json() # 如果 JSON 解码失败, r.json() 就会抛出一个异常。
r = requests.get('https://github.com/timeline.json', stream=True)r.raw # 获取来自服务器的原始套接字响应,请你确保在初始请求中设置了 stream=True
r = requests.get("url")
url中添加请求参数以字典形式传入url查询参数
payload = {'key1': 'value1', 'key2': 'value2'}r = requests.get("http://httpbin.org/get", params=payload)
则此时的URL就变成了:
http://httpbin.org/get?key2=value2&key1=value1
注意字典里值为 None 的键都不会被添加到 URL 的查询字符串里。
将列表作为值传入
payload = {'key1': 'value1', 'key2': ['value2', 'value3']}r = requests.get('http://httpbin.org/get', params=payload)
此时完整的url就变成了:
http://httpbin.org/get?key1=value1&key2=value2&key2=value3
GET请求中添加请求头部
headers = {'content-type': 'application/json'}r = requests.get("http://httpbin.org/get", params=payload, headers=headers)
注意: 所有的 header 值必须是
string、bytestring 或者 unicode。
POST请求:发送表单形式数据注意,在POST请求中,我们是一定要有请求参数的,二Get中是不一定需要请求参数的。
payload = {'key1': 'value1', 'key2': 'value2'}payload = (('key1', 'value1'), ('key1', 'value2'))response = requests.post("http://httpbin.org/post", data=payload)
payload = {'some': 'data'}r = requests.post(url, data=json.dumps(payload))
files = {'file': open('filename', 'rb')}r = requests.post(url, files=files)
r.status_code # 查看响应状态吗r.status_code = requests.codes.ok #查看状态码是否ok
如果请求失败(返回的状态码不是202),则可以用r.raise_for_status()来抛出异常。
r.raise_for_status()Traceback (most recent call last):File "requests/models.py", line 832, in raise_for_statusraise http_errorrequests.exceptions.HTTPError: 404 Client Error# 当返回状态码为200时,该函数返回为None
cookies = dict(cookies_are='working')response = requests.get(url, cookies=cookies)
response.cookies['cookie_name']
默认情况下,除了 HEAD, Requests 会自动处理所有重定向。
可以使用响应对象的
history方法来追踪重定向。
response.history# 禁用重定向处理response = requests.get('http://github.com', allow_redirects=False)# 对HEAD启用重定向response = requests.head('http://github.com', allow_redirects=True)
所有的生产代码都应该使用这一参数。如果不使用,你的程序可能会永远失去响应:
requests.get('http://github.com', timeout=0.001)
timeout并不是整个下载响应的时间限制,而是如果服务器在timeout秒内没有应答,将会引发一个异常.
- 遇到网络问题(如:DNS 查询失败、拒绝连接等)时,Requests 会抛出一个
ConnectionError异常。- HTTP 请求返回了不成功的状态码,
Response.raise_for_status()会抛出一个HTTPError异常。- 请求超时,则抛出一个
Timeout异常。- 请求超过了设定的最大重定向次数,则会抛出一个
TooManyRedirects异常。- Requests显式抛出的异常都继承自
requests.exceptions.RequestException。
