【问题标题】:Download pdfs with python用python下载pdf
【发布时间】:2021-06-30 10:15:31
【问题描述】:

我正在尝试下载位于单个 URL 中不同超链接中的多个 PDF。我的方法是首先根据 link 检索包含包含 PDF 的 "fileEntryId" 文本的 URL,然后尝试使用这种方法 link 下载 PDF 文件。

到目前为止,这是“我的”代码:

import httplib2
from bs4 import BeautifulSoup, SoupStrainer
import re
import os
import requests
from urllib.parse import urljoin


http = httplib2.Http()
status, response = http.request('https://www.contraloria.gov.co/resultados/proceso-auditor/auditorias-liberadas/regalias/auditorias-regalias-liberadas-ano-2015')

for link in BeautifulSoup(response, 'html.parser', parse_only=SoupStrainer('a', href=re.compile('.*fileEntryId.*'))):
    if link.has_attr('href'):
        x=link['href']
        
        #If there is no such folder, the script will create one automatically
        folder_location = r'c:\webscraping'
        if not os.path.exists(folder_location):os.mkdir(folder_location)

        response = requests.get(x)
        soup= BeautifulSoup(response.text, "html.parser")     
        for link in soup.select("x"):
            #Name the pdf files using the last portion of each link which are unique in this case
            filename = os.path.join(folder_location,link['href'].split('/')[-1])
            with open(filename, 'wb') as f:
                f.write(requests.get(urljoin(url,link['href'])).content)

谢谢

【问题讨论】:

  • PDF 不是“嵌入的”。您是否查看过要获取的此页面的源代码?您正在搜索<x> 标签,我认为没有任何<x> 标签。页面很复杂
  • 嗨蒂姆,感谢您的反馈,我对问题进行了更改以避免误导性的解决方案。

标签: python pdf web-scraping


【解决方案1】:

在任何地方创建一个文件夹并将脚本放在该文件夹中。运行脚本时,您应该在文件夹中获取下载的 pdf 文件。如果由于某种原因该脚本对您不起作用,请确保检查您的 bs4 版本是否是最新的,因为我使用伪 css 选择器来定位所需的链接。

import requests
from bs4 import BeautifulSoup

link = 'https://www.contraloria.gov.co/resultados/proceso-auditor/auditorias-liberadas/regalias/auditorias-regalias-liberadas-ano-2015'

with requests.Session() as s:
    s.headers['User-Agent'] = 'Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/88.0.4324.150 Safari/537.36'
    res = s.get(link)
    soup = BeautifulSoup(res.text,"lxml")
    for item in soup.select("table.table > tbody.table-data td.first > a[href*='fileEntryId']"):
        inner_link = item.get("href")
        resp = s.get(inner_link)
        soup = BeautifulSoup(resp.text,"lxml")
        pdf_link = soup.select_one("a.taglib-icon:contains('Descargar')").get("href")
        file_name = pdf_link.split("/")[-1].split("?")[0]
        with open(f"{file_name}.pdf","wb") as f:
            f.write(s.get(pdf_link).content)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-05-02
    • 2020-08-04
    • 2016-02-22
    • 2017-09-21
    • 1970-01-01
    • 1970-01-01
    • 2016-01-03
    • 2021-03-19
    相关资源
    最近更新 更多