python3 urllib.request下载出错

124 阅读1分钟

image.png 提示证书错误 去阿里云购买并下载证书安装后,依旧有问题

查询了stackoverflow,找到一个解决方案:

import ssl
ctx = ssl.create_default_context()
ctx.check_hostname = False
ctx.verify_mode = ssl.CERT_NONE

html = urllib.request.urlopen('https://blahblah.com/something', context=ctx).read()

但是我的下载代码是:

def _download(file_name):
    file_path = dataset_dir + "/" + file_name
    
    if os.path.exists(file_path):
        return

    print("Downloading " + file_name + " ... ")
    urllib.request.urlretrieve(url_base + file_name, file_path)
    print("Done")

于是我将ctx传给urlretrieve的入参data:

urllib.request.urlretrieve(url_base + file_name, file_path, data=ctx)

再去urllib/request.py文件源码中,修改

def urlretrieve(url, filename=None, reporthook=None, data=None):
    with contextlib.closing(urlopen(url, data=None, context=data)) as fp:
    ...

然后再运行代码,成功下载文件