项目场景:
python爬虫urllib请求报错
问题描述
import urllib.request
url='https://movie.douban.com/'
headers={'User-Agent':'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/100.0.4896.127 Safari/537.36'}
#构建请求对象
req=urllib.request.Request(url,headers=headers)
#使用urlopen打开请求
resp=urllib.request.urlopen(req)
#从响应结果中读取数据
html=resp.read().decode('utf-8')
print(html)
完整的报错情况是:
urllib.error.URLError: <urlopen error [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: unable to get local issuer certificate (_ssl.c:1108)>
原因分析:
这是因为访问的网站是https://,需要SSL认证,而直接用urllib会导致本地验证失败。
解决方案:
只需要关闭ssl本地认证即可。
import ssl
ssl._create_default_https_context = ssl._create_unverified_context