python - 使用 request.get 时如何跳过字符串中的错误 url?
问题描述
我有一串 url 链接到我试图下载的 pdf。有些网址不好,但我的字符串有 41,000 长,所以我想使用 requests.get 的例外来传递这些网址并继续搜索和下载列表中的下一个。
我试过使用下面的 except 函数,我也尝试过其他一些格式和位置,但我似乎无法让它发挥作用。
try:
r = requests.get(url, allow_redirects=True)
r.raise_for_status()
with open(('file'+str(u)+'.pdf'),"wb") as code:
code.write(r.content)
print("pdf")
except requests.exceptions.HTTPError as err:
print(err)
sys.exit(1)
发生错误时,我会得到这种读数:
requests.exceptions.SSLError: HTTPSConnectionPool(host=
也
(Caused by SSLError(CertificateError("hostname
解决方案
尝试这个 :)
# urls is the list of url
for url in urls:
try:
r = requests.get(url, allow_redirects=True)
r.raise_for_status()
with open(('file'+str(u)+'.pdf'),"wb") as code:
code.write(r.content)
print("pdf")
except requests.exceptions.HTTPError as err:
print('[http_error]: {}'.format(err))
except requests.exceptions.SSLError as bad_url:
print('[bad_url]: {}'.format(bad_url))
except Exception as e:
print('[error]: {}'.format(e))
推荐阅读
- google-apps-script - 有没有办法在 Google-sheet 脚本中获取最后一个工作表名称?
- python - 在 Python3.8 中创建虚拟环境时出错
- laravel - 如何在 laravel 中使用 gentelella alela select2 选项
- github - 如何在 Git 项目的每个提交中获取提交者的用户名?
- python - 一旦变量超出限制,如何停止提问
- sql-server - SQL Server 数据工具 - Visual Studio 2015 错误
- c - 在链表的头部插入?
- django - 在 django admin 中显示外键对象内的相关数据
- javascript - 如何将数组映射添加到 Firestore 数据库?
- excel - 如何复制word页面并粘贴到excel中?