python-2.7 - 在 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()
解决方案
我会推荐requests
和fake-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
推荐阅读
- aws-lambda - EventBridge 消息是否总是进入 CloudWatch 日志?
- javascript - 单击按钮后程序两次进入 eventListener
- r - 如何根据字符串的匹配部分合并 R 中的两个数据框?
- java - 如何创建和初始化(在 Java 中)列表
在同一个声明中?(编者请注意:这*不*与列表相同 ) - matlab - 在 MATLAB 中验证 MPC 模型时出错
- python - pandas.read_sql 不返回所有记录
- javascript - CSS Flexbox 布局未按预期工作
- apache-nifi - NiFi ConsumeKafkaRecord 轮询的消息远远多于 max.poll.records
- angular - 即使使用 ngOnChanges,Angular @Input() 也不会更新父组件中的值
- refactoring - 如果 UI 中的名称已更改,我是否应该将内部引用重命名为功能名称?