官方文档真是好用的一匹
官方文档:https://2.python-requests.org//zh_CN/latest/index.html
参考blog:https://www.cnblogs.com/humiao-0626/category/1465538.html
1. 快速上手
# -*- coding:utf-8 -*-
"""
requests模块
https://2.python-requests.org//zh_CN/latest/index.html
"""
import requests#
1 发送请求
r = requests.get("https://www.cnblogs.com/") # r: Response 对象
print(r)
# 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")
2 传递url参数
# payload = {"key1":"value1","key2":"value2"}
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
print(r.url) # http://httpbin.org/get?key1=value1&key2=value2&key2=value3
3 响应内容
r = requests.get("https://api.github.com/events")
print(r.text)
# response 编码类型
print(r.encoding) # utf-8
print(r.content) # b'[{"id":"10124980852","type":"PushEvent","actor":{"id":387
# 比如 HTTP 和 XML 自身可以指定编码。
# 这样的话,你应该使用 r.content 来找到编码,
# 然后设置 r.encoding 为相应的编码。这
# 样就能使用正确的编码解析 r.text 了。
4 二进制响应内容
print(r.content) # # b'[{"id":"10124980852","type":"PushEvent","actor":{"id":387
# Requests 会自动为你解码 gzip 和 deflate 传输编码的响应数据。
# 以请求返回的二进制数据创建一张图片
'''
from PIL import Image
from io import BytesIO
i = Image.open(BytesIO(r.content))
'''
5 JSON响应内容
r = requests.get('https://api.github.com/events')
r.json() # b'[{"id":"10125000497","type":"PushEvent","actor":{"id":28391787,"login":"m1ha5","display_login":"m1"}}]
# 响应内容是 401 (Unauthorized),尝试访问 r.json() 将会抛出 ValueError: No JSON object could be decoded 异常。
# 要检查请求是否成功,请使用 r.raise_for_status() 或者检查 r.status_code 是否和你的期望相同
# print(r.raise_for_status())
print(r.status_code)
6 原始响应内容
# 想获取来自服务器的原始套接字响应
# 确保在初始请求中设置了 stream=True
r= requests.get('https://api.github.com/events', stream=True)
print(r.raw) # <urllib3.response.HTTPResponse object at 0x000001D3FD5525C0>
# print(r.raw.read(10)) # b'\x1f\x8b\x08\x00\x00\x00\x00\x00\x00\x03'
# 下面的模式将文本流保存到文件
with open('test.txt','wb') as fd:
for chunk in r.iter_content(chunk_size=10):
fd.write(chunk)
7 定制请求头
url = "https://api.github.com/some/endpoint"
headers = {'user-agent':'my-app/0.0.1'}
r = requests.get(url,headers=headers)
# 定制 header 的优先级低于某些特定的信息源
# 注意: 所有的 header 值必须是 string、bytestring 或者 unicode。
8 更加复杂的 POST 请求
url = 'http://httpbin.org/post'
# payload = {'key1':'vaule1','key2':'value2'}
# 为 data 参数传入一个元组列表。在表单中多个元素使用同一 key 的时候,这种方式尤其有效:
payload = (('key1','value1'),('key1','value1'))
r = requests.post(url=url,data=payload)
print(r.text) # 返回response的内容
# 发送的数据并非编码为表单形式 你传递一个 string
# 例如,Github API v3 接受编码为 JSON 的 POST/PATCH 数据:
import json
url = 'https://api.github.com/some/endpoint'
payload = {'some':'data'}
# 自行对dict进行编码
# r = requests.post(url=url,data=json.dumps(payload))
# 用 json 参数直接传递
r = requests.post(url=url,json=payload)
print(r.text)
9 POST一个多部分编码(Multipart-Encoded)的文件
官方文档
10 响应状态码
url = "http://httpbin.org/get"
r = requests.get(url=url)
print(r.status_code)
print(r.status_code == requests.codes.ok) # True # Requests还附带了一个内置的状态码查询对象
# if 发送了一个错误请求(一个 4XX 客户端错误,或者 5XX 服务器错误响应),
# 我们可以通过 Response.raise_for_status() 来抛出异常
url="http://httpbin.org/status/404"
bad_r = requests.get(url=url)
print(bad_r.status_code)
# print(bad_r.raise_for_status())
11 响应头
print(r.headers) # 字典
'''
{
'Access-Control-Allow-Credentials': 'true',
'Access-Control-Allow-Origin': '*',
'Content-Encoding': 'gzip',
'Content-Type': 'application/json',
'Date': 'Thu, 01 Aug 2019 02:59:19 GMT',
'Referrer-Policy': 'no-referrer-when-downgrade',
'Server': 'nginx',
'X-Content-Type-Options': 'nosniff',
'X-Frame-Options': 'DENY',
'X-XSS-Protection': '1; mode=block',
'Content-Length': '184',
'Connection': 'keep-alive'
}
'''
print(r.headers['Content-Type'])
print(r.headers.get('Content-Type'))
# 服务器可以多次接受同一 header,每次都使用不同的值
12 cookie
# 某个响应中包含一些 cookie,你可以快速访问它们
url = 'http://example.com/some/cookie/setting/url'
r = requests.get(url=url)
print(r.cookies) # <RequestsCookieJar[]>
# print(r.cookies['example_cookie_name'])
# 发送你的cookies到服务器,可以使用 cookies 参数
url= 'http://httpbin.org/cookies'
cookies = dict(cookies_are='working')
r = requests.get(url=url,cookies=cookies)
print(r.text) # '{"cookies": {"cookies_are": "working"}}'
# 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=url,cookies=jar)
print(r.text) # '{"cookies": {"tasty_cookie": "yum"}}'
#
13 重定向与请求历史
官方文档
14 超时错误
# requests 在经过以 timeout 参数设定的秒数时间之后停止等待响应
# 基本上所有的生产代码都应该使用这一参数
# 如果不使用,你的程序可能会永远失去响应:
requests.get('http://github.com', timeout=0.001)
'''
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
requests.exceptions.Timeout: HTTPConnectionPool(host='github.com', port=80): Request timed out. (timeout=0.001)
'''
'''
timeout 仅对连接过程有效,与响应体的下载无关
timeout 并不是整个下载响应的时间限制,而是如果服务器在 timeout 秒内没有应答,将会引发一个异常
是在 timeout 秒内没有从基础套接字上接收到任何字节的数据时
'''
15 错误与异常
'''
遇到网络问题(如:DNS 查询失败、拒绝连接等)时,Requests 会抛出一个 ConnectionError 异常。
如果 HTTP 请求返回了不成功的状态码, Response.raise_for_status() 会抛出一个 HTTPError 异常。
若请求超时,则抛出一个 Timeout 异常。
若请求超过了设定的最大重定向次数,则会抛出一个 TooManyRedirects 异常。
所有Requests显式抛出的异常都继承自 requests.exceptions.RequestException 。
'''