【发布时间】: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