首页 > 解决方案 > 使用 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”放在哪里?

标签: pythonpdfbeautifulsouppython-requestspython-requests-html

解决方案


.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')}")


推荐阅读