【问题标题】:Web scraping - saving files to nested folders网页抓取 - 将文件保存到嵌套文件夹
【发布时间】:2021-03-14 02:20:57
【问题描述】:

我正在使用内置 API 从不同的 URL 下载 pdf 文件。

我的最终结果应该是将文件从每个唯一链接(在下面的代码中标识为links)下载到桌面上的唯一文件夹(代码中的folder_location)。

我对如何安排代码来做到这一点感到很困惑,因为我还是个新手。到目前为止,我已经尝试了以下方法。

import os
import requests
from glob import glob
import time
from urllib.parse import urljoin
from bs4 import BeautifulSoup

links = ["P167897", "P173997", "P166309"]

folder_location = "/pdf/"


for link, folder in zip(links, folder_location):
    time.sleep(10)
    end_point = f"https://search.worldbank.org/api/v2/wds?" \
                f"format=json&includepublicdocs=1&" \
                f"fl=docna,lang,docty,repnb,docdt,doc_authr,available_in&" \
                f"os=0&rows=20&proid={link}&apilang=en"
    documents = requests.get(end_point).json()["documents"]
    for document_data in documents.values():
        try:
            pdf_url = document_data["pdfurl"]
            filename = os.path.join(folder,pdf_url.split('/')[-1])
            with open(filename, 'wb') as f:
                f.write(requests.get(pdf_url).content)

编辑:澄清一下,links 中的对象是 id,基于要从 API 识别到 pdf 文件的链接。

【问题讨论】:

    标签: python python-3.x web-scraping python-requests


    【解决方案1】:

    您可以尝试使用pathlib 模块。

    方法如下:

    import os
    import time
    from pathlib import Path
    
    import requests
    
    links = ["P167897", "P173997", "P166309"]
    
    for link in links:
        end_point = f"https://search.worldbank.org/api/v2/wds?" \
                    f"format=json&includepublicdocs=1&" \
                    f"fl=docna,lang,docty,repnb,docdt,doc_authr,available_in&" \
                    f"os=0&rows=20&proid={link}&apilang=en"
        documents = requests.get(end_point).json()["documents"]
        for document_data in documents.values():
            try:
                pdf_url = document_data["pdfurl"]
                file_path = Path(f"pdf/{link}/{pdf_url.rsplit('/')[-1]}")
                file_path.parent.mkdir(parents=True, exist_ok=True)
                with file_path.open("wb") as f:
                    f.write(requests.get(pdf_url).content)
                time.sleep(10)
            except KeyError:
                continue
    

    这会将文件输出到:

    pdf/
    └── P167897
        ├── Official-Documents-First-Restatement-to-the-Disbursement-Letter-for-Grant-D6810-SL-and-for-Additional-Financing-Grant-TF0B4694.pdf
        └── Official-Documents-Grant-Agreement-for-Additional-Financing-Grant-TF0B4694.pdf
        ...
    

    【讨论】:

    • 谢谢! pathlib 很有帮助!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-02-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多