首页 > 解决方案 > 在 python 上下载文件被禁止 http 403

问题描述

我一直在尝试使用 Python 2.7从链接http://www.py4e.com/code3/mbox.txt下载文件,但它一直在说:

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

我正在使用的代码是:

req = Request('http://www.py4e.com/code3/mbox.txt', headers={'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36'})

webpage = urlopen(req).read()

标签: python-2.7http-error

解决方案


我会推荐requestsfake-useragent

首先,确保您已经使用命令行安装了它们:

pip install requests fake-useragent

然后使用:

import requests
from fake_useragent import UserAgent

ua_str = UserAgent().chrome
url = "https://www.py4e.com/code3/mbox.txt"
r = requests.get(url, headers={"User-Agent": ua_str})
txt = r.content

推荐阅读