python - 使用 Beautiful Soup/Requests 下载 HTML 中 URL 不完整的 PDF
问题描述
我想下载页面https://www.mdpi.com/search?authors=University+of+Alabama%2C+Tuscaloosa上列出的所有 259 个 PDF ,例如:
<a href="/1424-8220/21/19/6384/pdf" class="UD_Listings_ArticlePDF" onclick="if (!window.__cfRLUnblockHandlers) return false; ga('send', 'pageview', '/1424-8220/21/19/6384/pdf');" title="Article PDF" data-cf-modified-fa685c2bcda960230d46973e-="">
<i class="material-icons">get_app</i>
</a>
href 只有域之后的 URL 部分,所以完整的 URL 是https://mdpi.com/1424-8220/21/19/6384/pdf。
当我运行它来下载文件时:
for link in links:
if ('/pdf' in link.get('href', [])):
i += 1
print("Downloading file: ", i)
response = requests.get(link.get('href'))
我得到这个回溯:
requests.exceptions.MissingSchema: Invalid URL '/1424-8220/21/19/6384/pdf': No schema supplied. Perhaps you meant http:///1424-8220/21/19/6384/pdf?
我将 URL 的缺失部分“https://mdpi.com”放在哪里?
解决方案
.get()
正在接受一个字符串,所以 f-string 应该可以工作。
for link in links:
if ('/pdf' in link.get('href', [])):
i += 1
print("Downloading file: ", i)
response = requests.get(f"https://mdpi.com{link.get('href')}")
推荐阅读
- javafx - 指定的文件夹不包含 Java 平台
- c# - 实体框架:如何为批量操作建模
- python - 如何启用棉花糖枚举 EnumField 以正确序列化 EnumField?
- python - 如何找到坐标系的最小经度?
- haskell - Traversable[]和Applicative Maybe在镜头库中的使用效果
- google-kubernetes-engine - 是否可以在 GKE 中为 Filestore 设置 GID/UID?
- c++ - 如果我将 glUniform1f 调用放在渲染循环之前,则不会存储统一值
- powerbi - power bi报告中如何实现前两列或前三列的冻结
- c# - 使用 FileUpload 回发后保留所选文件
- python - habitat-api 快速启动无法正常运行 - qt.qpa.plugin: 在“”中找不到 Qt 平台插件“cocoa”