Error:urllib.error.URLError: <urlopen error [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c:xxx)>
Solution:
Add the following codes before you use urllib.request.Request(url)
:
import ssl
ssl._create_default_https_context = ssl._create_unverified_context
Problem analysis
This is because the website visited is HTTPS://
, which requires SSL authentication, and using urllib
directly will lead to local authentication failure (the specific reason is not found out), so SSL is used_create_unverified_Context
turn off authentication
Error recurrence
When request = urllib.Request.Request (URL, data)
is executed, an error is reported. Cancel the comments in the upper two lines to solve the problem
import json
import urllib
def baidu_search():
url = "https://www.baidu.com/s?"
data = {"wd": "AHA"}
data = json.dumps(data).encode('GBK')
# import ssl
# ssl._create_default_https_context = ssl._create_unverified_context # If these two lines are not added, the next line reports an error
request = urllib.request.Request(url, data)
response = urllib.request.urlopen(request)
content = response.read()
print(str(content))
if __name__ == '__main__':
baidu_search()