📅  最后修改于: 2020-10-21 08:35:01             🧑  作者: Mango
SSL证书是安全URL附带的一项安全功能。使用Requests库时,它还会验证给定https URL的SSL证书。默认情况下,Requests模块会启用SSL验证,如果不存在证书,则会引发错误。
以下是使用安全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证书,并使用verify参数提供路径,如下所示。
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"
}
}
]