requests 使用要点

使用 requests 配合抓包工具调试

使用 requests 对 https 地址提交查询时,如果在调试程序时使用抓包工具抓取数据包,会导致程序报错中断,抓包工具中也无法抓取取数据。
这是因为默认情况下,requests 会启用SSL验证,在打开抓包工具时,如果无法验证SSL证书会导致:

requests.exceptions.SSLError: ("bad handshake: Error([('SSL routines', 'tls_process_server_certificate', 'certificate verify failed')],)",)

为解决此问题,可以关闭 requests 的 SSL 验证

# 在 requests 中加入 verify=False
res = requests.get(url, verify=False)

关闭 SSL 验证后,会提示

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)

解决方法:

from requests.packages.urllib3.exceptions import InsecureRequestWarning
# 禁用安全请求警告
requests.packages.urllib3.disable_warnings(InsecureRequestWarning)

这时使用运行程序就没有错误信息与警告了,使用抓包工具也可以正常抓包了。

r.text 返回乱码

# 直接使用 r.txext 乱码,因此对 r.content 解码
print(r.content.decode('gbk'))
posted @ 2023-04-13 17:12  汉学  阅读(55)  评论(0)    收藏  举报