【问题标题】:Download PDFs with incomplete URLs in HTML with Beautiful Soup/Requests使用 Beautiful Soup/Requests 下载 HTML 中 URL 不完整的 PDF
【发布时间】:2021-09-27 20:07:43
【问题描述】:

我想下载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”放在哪里?

【问题讨论】:

    标签: python pdf beautifulsoup python-requests python-requests-html


    【解决方案1】:

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

    【讨论】:

    • 你知道为什么它只下载了15个PDF吗?这里的搜索结果显示 259。mdpi.com/search?authors=University+of+Alabama%2C+Tuscaloosa
    • 好吧,首先 - 你唯一的if 说所有链接都带有/pdf,所以也许只有15 个链接有这个/pdf?第二件事 - 页面限制为 50 个结果,无论如何您都无法下载 259 个。您必须迭代 tru 分页。
    • @BrianC。如果类名仍然相同,也许这可以帮助您获得更好的结果。 results = soup.find_all(attrs={"class": re.compile(r"^UD_Listings_ArticlePDF$", re.I)})
    • 谢谢,我一次仍然可以得到 15 个结果。我很困惑,因为我希望在查看视图页面源时找到 50 个引用的 pdf,但无论我设置的每页结果数量如何,它总是 15 个。
    • 尝试显示更多代码,也许我们能找到问题所在。你有什么错误吗?或者您在links 列表中有 15 项?
    猜你喜欢
    • 2019-07-21
    • 1970-01-01
    • 2013-08-01
    • 2016-06-08
    • 1970-01-01
    • 2021-09-24
    • 2016-11-16
    • 2021-12-05
    • 1970-01-01
    相关资源
    最近更新 更多