使用urllib下载数据时的证书验证失败以及403Forbidden错误

使用urllib下载数据

1、使用urllib.request向m.tianqi.com发送请求、获取该网站的响应
2、再使用Python的re模块来解析服务器响应、从中提取天气数据

import urllib.request, re

def get_html (city, year, month):
    url = 'https://m.tianqi.com/lishi/%s/%s%s.html' % (city, year, month)
    return urllib.request.urlopen(url).read().decode('UTF-8')
print(get_html('guangzhou','2018', '01'))

报错:

脚本提示证书验证失败

urllib.error.URLError: <urlopen error [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: unable to get local issuer certificate (_ssl.c:1108)>

解决方案:

在开头取消证书验证

# 全局取消证书验证

import ssl
ssl._create_default_https_context = ssl._create_unverified_context

再次运行程序,

报错:

urllib.error.HTTPError: HTTP Error 403: Forbidden

解决方案:

urllib.request.urlopen 方式打开一个URL,服务器端只会收到一个单纯的对于该页面访问的请求,但是服务器并不知道发送这个请求使用的浏览器,操作系统,硬件平台等信息,而缺失这些信息的请求往往都是非正常的访问,例如爬虫.

有些网站为了防止这种非正常的访问,会验证请求信息中的UserAgent(它的信息包括硬件平台、系统软件、应用软件和用户个人偏好),如果UserAgent存在异常或者是不存在,那么这次请求将会被拒绝(如上错误信息所示)

加上浏览器伪装就可以了。

import urllib.request, re
import ssl
ssl._create_default_https_context = ssl._create_unverified_context

def get_html (city, year, month):
    url = 'https://m.tianqi.com/lishi/%s/%s%s.html' % (city, year, month)
    requst = urllib.request.Request(url)
    # 设置一个User-Agent头,避免产生403错误
    requst.add_header('User-Agent', 'Mozilla/5.0')
    return urllib.request.urlopen(requst).read().decode('UTF-8')
print(get_html('guangzhou','2018', '01'))

问题成功解决。

原创文章 214 获赞 359 访问量 89万+

猜你喜欢

转载自blog.csdn.net/yxys01/article/details/104185118