目录
1.读取响应的内容
1)文本
import requests
r = requests.get(url)
Requests 会根据响应的 Content-Type 头信息自动解码,大多数 unicode 字符集都能被无缝地解码:
>>> r.text
使用 r.encoding 来看 Requests 用什么编码方式解码。还可以设置 r.encoding
让 Requests 用这种编码方式解码:
>>> r.encoding
'utf-8'
2)JSON 数据格式
Requests 内置了 JSON 解码器,直接对 JSON 数据格式的响应内容解码:
>>> r.json()
3)二进制数据格式
Requests 会自动解码 gzip
和 deflate
编码方式的响应内容。
>>> r.content
4)原始的
要获取原始的响应内容,需要先在 requests 请求中加上关键字参数 stream=True,再使用 r.raw :
>>> r = requests.get(url, 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'
2.响应状态码的校验
1. 如果请求的响应错误(4xx客户端错误,5xx服务器错误),r.raise_for_status() 会抛出异常:
>>> r.raise_for_status()
Traceback (most recent call last):
File "test.py", line 4, in raise_for_status
raise http_error
requests.exceptions.HTTPError: 404 Client Error
2. requests 提供了一个内置的状态码查询对象 requests.codes,示例:
if r.status_code == requests.codes.ok :
print("Requests succesfully")
使用 requests.codes.ok 校验响应的状态码,和“200”相比更加直观。
状态码和对应的 requests.codes 属性:
3.post请求上传文件
files = {'file' : open('file', 'rb')}
requests.post(url,files=files)
4.Cookies 获取
url = "https://www.baidu.com"
with requests.get(url) as r:
print(r.cookies)
for k,v in r.cookies.items():
print(k,v)
<RequestsCookieJar[<Cookie BDORZ=27315 for .baidu.com/>]>
BDORZ 27315
5.Session 对象
在 requests 中,直接利用 get 或 post 的确可以做到模拟网页的请求,但是这相当于用两个浏览器打开了不同的页面,怎么让所有请求之间保持 cookie?
可以获取前一个请求的 cookie 并在后二个请求中设置,但这样太麻烦。
使用 requests 提供的 Session 对象能够跨请求保持某些参数,还能在同一个 Session 实例发出的所有请求之间保持 cookie。
示例:
s = requests.Session()
s.get(geturl,params=params)
s.post(posturl,data=data)
...
6.请求SSL证书错误的网站
使用 HTTPS 协议的网站如果没有设置好 HTTPS 证书,或者网站的 HTTPS 证书不被 CA 机构认可,这些网站浏览器打开时会提示「您的连接不是私密连接」这样的错误。这样的网站如果直接 requests 请求,会直接抛出 SSLError 错误。
要爬取这个网站怎么办呢?
请求的 verify 参数控制是否验证证书。verify 参数默认值是True,验证请求 url 的SSL证书。将其设置为False,在请求时就不会再验证证书是否有效。
requests.get(url,verify=False)
7.设置请求的超时时间
请求的 timeout 参数设置超时时间,timeout 参数默认是 None,不做超时处理,一直等待服务器返回响应。
要设置超时时间,对 timeout 参数设置数值,如果在这个时间没有响应,抛出超时异常。
示例:
requests.get(url,timeout=1) #超时时间1s
8.设置OAuth 认证
requests.get(url,auth=('username','password'))
9.代理设置
某些网站在测试的时候请求几次,能正常获取内容。但是对于大规模且频繁的请求,网站可能会弹出验证码,或者跳转到登录认证页面,更甚者可能会直接封禁客户端的 IP,导致一定时间段内无法访问。
在请求的 proxies 参数设置代理,从而避免这种情况发生。
示例:
proxies = {
"http": "http://10.10.1.10:3128",
"https": "http://10.10.1.10:1080",
} #示例代理
requests.get(url, proxies=proxies)
10.Prepared Request
请求在 requests 内部的实现
11.requests.request 函数源码
def request(method, url, **kwargs):
"""Constructs and sends a :class:`Request <Request>`.
:param method: method for the new :class:`Request` object: ``GET``, ``OPTIONS``, ``HEAD``, ``POST``, ``PUT``, ``PATCH``, or ``DELETE``.
:param url: URL for the new :class:`Request` object.
:param params: (optional) Dictionary, list of tuples or bytes to send
in the query string for the :class:`Request`.
:param data: (optional) Dictionary, list of tuples, bytes, or file-like
object to send in the body of the :class:`Request`.
:param json: (optional) A JSON serializable Python object to send in the body of the :class:`Request`.
:param headers: (optional) Dictionary of HTTP Headers to send with the :class:`Request`.
:param cookies: (optional) Dict or CookieJar object to send with the :class:`Request`.
:param files: (optional) Dictionary of ``'name': file-like-objects`` (or ``{'name': file-tuple}``) for multipart encoding upload.
``file-tuple`` can be a 2-tuple ``('filename', fileobj)``, 3-tuple ``('filename', fileobj, 'content_type')``
or a 4-tuple ``('filename', fileobj, 'content_type', custom_headers)``, where ``'content-type'`` is a string
defining the content type of the given file and ``custom_headers`` a dict-like object containing additional headers
to add for the file.
:param auth: (optional) Auth tuple to enable Basic/Digest/Custom HTTP Auth.
:param timeout: (optional) How many seconds to wait for the server to send data
before giving up, as a float, or a :ref:`(connect timeout, read
timeout) <timeouts>` tuple.
:type timeout: float or tuple
:param allow_redirects: (optional) Boolean. Enable/disable GET/OPTIONS/POST/PUT/PATCH/DELETE/HEAD redirection. Defaults to ``True``.
:type allow_redirects: bool
:param proxies: (optional) Dictionary mapping protocol to the URL of the proxy.
:param verify: (optional) Either a boolean, in which case it controls whether we verify
the server's TLS certificate, or a string, in which case it must be a path
to a CA bundle to use. Defaults to ``True``.
:param stream: (optional) if ``False``, the response content will be immediately downloaded.
:param cert: (optional) if String, path to ssl client cert file (.pem). If Tuple, ('cert', 'key') pair.
:return: :class:`Response <Response>` object
:rtype: requests.Response
Usage::
>>> import requests
>>> req = requests.request('GET', 'https://httpbin.org/get')
>>> req
<Response [200]>
"""
# By using the 'with' statement we are sure the session is closed, thus we
# avoid leaving sockets open which can trigger a ResourceWarning in some
# cases, and look like a memory leak in others.
with sessions.Session() as session:
return session.request(method=method, url=url, **kwargs)
12.获取请求花费时间
官方文档定义:
从发送请求到响应到达之间经过的时间量(以时间增量表示)。此属性专门测量从发送请求的第一个字节到完成对头的分析所用的时间。因此,它不受使用响应内容或stream关键字参数值的影响。
import requests
url = "https://www.zhihu.com/hot"
with requests.get(url) as r:
time = r.elapsed.total_seconds()
print(time)
结果:
5.085971
13.响应
参考: