一、requests.utils.dict_from_cookiejar() 把cookie对象转化为字典
import requests
response = requests.get("http://www.baidu.com")
response.cookies
>>> <RequestsCookieJar[Cookie(version=0, name='BDORZ', value='27315', port=None,
port_specified=False, domain='.baidu.com', domain_specified=True, domain_initial_dot=True,
path='/', path_specified=True, secure=False, expires=1563633603, discard=False,
comment=None, comment_url=None, rest={}, rfc2109=False)]>
requests.utils.dict_from_cookiejar(response.cookies)
>>>{'BDORZ': '27315'}
调用response.cookies时可以看出打印出来的是一堆东西;但是当转换为字典时,只对应一个键值对。这是因为本次请求百度时,服务器可能只向本地设置一个cookie,也可能设置所有cookie。若只设置一条cookie,剩余的cookie可能是在其他请求时分批设置到本地。
反过来:将字典转换为cookie对象
requests.utils.cookiejar_from_dict({'BDORZ': '27315'})
>>> <RequestsCookieJar[Cookie(version=0, name='BDORZ', value='27315', port=None,
port_specified=False, domain='', domain_specified=False, domain_initial_dot=False,
path='/', path_specified=True, secure=False, expires=None, discard=True, comment=None,
comment_url=None, rest={'HttpOnly': None}, rfc2109=False)]>
二、requests.utils.unquote() 对已编码的url地址进行解码
requests.utils.quote("中华有为")
>>> '%E4%B8%AD%E5%8D%8E%E6%9C%89%E4%B8%BA'
requests.utils.unquote("%E4%B8%AD%E5%8D%8E%E6%9C%89%E4%B8%BA")
>>> '中华有为'
常用于获取url中的内容。
三、请求SSL证书验证
有时候打开某个网站时会弹出不是私密链接,如图所示。对于这样的网站直接爬取肯定是有问题的。
requests.get("https://www.12315.cn/")
>>> SSLError: HTTPSConnectionPool(host='www.12315.cn', port=443): Max retries exceeded with
url: / (Caused by SSLError(SSLError("bad handshake: Error([('SSL routines',
'tls_process_server_certificate', 'certificate verify failed')])")))
报错!应在请求里面添加verify=False属性:
requests.get("https://www.12315.cn/", verify=False)
>>> D:\anaconda3\lib\site-packages\urllib3\connectionpool.py:847: InsecureRequestWarning:
Unverified HTTPS request is being made. Adding certificate verification is strongly
advised. See: https://urllib3.readthedocs.io/en/latest/advanced-usage.html#ssl-warnings
InsecureRequestWarning)
虽然产生警告,但不影响代码执行。
四、设置超时参数
打开一个网站时,可能因为网速不是很好,要等待很长时间。那么对于一个程序来说,执行的效率就很低了而且不知道程序在哪里出现的问题。所以可以添加一个超时参数,若在设定时间内成功响应则程序继续向下走,若超时则报错,强行保证每个请求不会花太多时间。
response = requests.get("http://www.baidu.com", timeout=3)
这样存在一个问题,例如当我们请求很多url地址时,难免有一个url地址响应的比较慢。这样程序就会报错。怎么解决这个问题呢?平时遇到网页在一直转刷新不出来的情况时,我们往往会刷新一下。所以可以用代码刷新一下,也就是重新请求一下。 这就要重新引入一个模块--retrying。
import requests
from retrying import retry
@retry(stop_max_attempt_number=3) # 最多重新执行3次
def requrl(url):
print("="*10) # 检验是否执行了3次
response = requests.get(url, timeout=3)
html_str = response.content.decode()
return html_str
try:
print(requrl("www.baidu.com")) # 输入错误的ip地址,模拟请求失败。 正确url:"http://www.baidu.com"
except:
print("请求失败!")
>>>
==========
==========
==========
请求失败!
五、配合状态码判断是否请求成功
import requests
response = requests.get("http://www.baidu.com")
try:
assert response.status_code == 200
except:
print("请求失败!")
若单纯使用assert,请求失败时会报错。所以配合try-except处理这个错误。