- 请求教程
- 请求 - 主页
- 请求 - 概述
- 请求 - 环境设置
- 请求 - Http 请求如何工作?
- 请求 - 处理请求
- 处理 HTTP 请求的响应
- 请求 - HTTP 请求标头
- 请求 - 处理 GET 请求
- 处理 POST、PUT、PATCH 和 DELETE 请求
- 请求 - 文件上传
- 请求 - 使用 Cookie
- 请求 - 处理错误
- 请求 - 处理超时
- 请求 - 处理重定向
- 请求 - 处理历史记录
- 请求 - 处理会话
- 请求 - SSL 认证
- 请求 - 身份验证
- 请求 - 事件挂钩
- 请求 - 代理
- 请求 - 使用请求进行网页抓取
- 请求有用的资源
- 请求 - 快速指南
- 请求 - 有用的资源
- 请求 - 讨论
请求 - SSL 认证
SSL 证书是一种安全功能,附带安全 URL。当您使用 Requests 库时,它还会验证给定 https URL 的 SSL 证书。默认情况下,请求模块中启用 SSL 验证,如果证书不存在,则会抛出错误。
使用安全 URL
以下是使用安全 URL 的示例 -
import requests getdata = requests.get(https://jsonplaceholder.typicode.com/users) print(getdata.text)
输出
E:\prequests>python makeRequest.py [ { "id": 1, "name": "Leanne Graham", "username": "Bret", "email": "Sincere@april.biz", "address": { "street": "Kulas Light", "suite": "Apt. 556", "city": "Gwenborough", "zipcode": "92998-3874", "geo": { "lat": "-37.3159", "lng": "81.1496" } }, "phone": "1-770-736-8031 x56442", "website": "hildegard.org", "company": { "name": "Romaguera-Crona", "catchPhrase": "Multi-layered client-server neural-net", "bs": "harness real-time e-markets" } } ]
我们很容易从上面的 https URL 得到响应,这是因为请求模块可以验证 SSL 证书。
您只需添加 verify=False 即可禁用 SSL 验证,如下例所示。
例子
import requests getdata = requests.get('https://jsonplaceholder.typicode.com/users', verify=False) print(getdata.text)
您将得到输出,但它也会给出一条警告消息,表明 SSL 证书未经过验证,建议添加证书验证。
输出
E:\prequests>python makeRequest.py connectionpool.py:851: InsecureRequestWarning: Unverified HTTPS request is being made. Adding certificate verification is strongly advised. See: https://urllib3 .readthedocs.io/en/latest/advanced-usage.htm l#ssl-warnings InsecureRequestWarning) [ { "id": 1, "name": "Leanne Graham", "username": "Bret", "email": "Sincere@april.biz", "address": { "street": "Kulas Light", "suite": "Apt. 556", "city": "Gwenborough", "zipcode": "92998-3874", "geo": { "lat": "-37.3159", "lng": "81.1496" } }, "phone": "1-770-736-8031 x56442", "website": "hildegard.org", "company": { "name": "Romaguera-Crona", "catchPhrase": "Multi-layered client-server neural-net", "bs": "harness real-time e-markets" } } ]
您还可以通过将 SSL 证书托管在您的一端来验证 SSL 证书,并使用验证参数提供路径,如下所示。
例子
import requests getdata = requests.get('https://jsonplaceholder.typicode.com/users', verify='C:\Users\AppData\Local\certificate.txt') print(getdata.text)
输出
E:\prequests>python makeRequest.py [ { "id": 1, "name": "Leanne Graham", "username": "Bret", "email": "Sincere@april.biz", "address": { "street": "Kulas Light", "suite": "Apt. 556", "city": "Gwenborough", "zipcode": "92998-3874", "geo": { "lat": "-37.3159", "lng": "81.1496" } }, "phone": "1-770-736-8031 x56442", "website": "hildegard.org", "company": { "name": "Romaguera-Crona", "catchPhrase": "Multi-layered client-server neural-net", "bs": "harness real-time e-markets" } } ]