首页 > 解决方案 > 搜索和下载包含在 pandas df 链接列中的 pdf 文件

问题描述

我有一个三列的 df [[SerieFecha, Título, Link]]。我想创建一个循环,遍历 ['Link'] 列中的每个链接以查找和下载嵌入的 pdf 文件。

我设法一次完成一个链接。但这种方法显然效率不高。

这是我到目前为止所做的。

import requests
from requests import get
from bs4 import BeautifulSoup
import pandas as pd
import numpy as np

url = "http://legislaturautuado.com/pgs/resolutions.php?st=5&f=2016"
r = requests.get(url)
html_table = BeautifulSoup(r.text).find('table')
r.close()
df = pd.read_html(str(html_table), header=0)[0]
df['Link'] = [link.get('href') for link in html_table.find_all('a')]
df.head()

df

然后我使用找到的第一个链接来搜索它包含的 .pdf 链接。

df.iloc[0,2]

'http://legislaturautuado.com/pgs/docviewer.php?p=1182&pt=2&d=1-2016-2017&dt=2'

import urllib.request
my_url = 'http://legislaturautuado.com/pgs/docviewer.php?p=1182&pt=2&d=1-2016-2017&dt=2'
html=urllib.request.urlopen(my_url).read()
sopa = BeautifulSoup(html)
current_link = ''
for link in sopa.find_all('a'):
    current_link = link.get('href')
    if current_link.endswith('pdf'):
      print('Mi pdf: ' + current_link)

[输出]Mi pdf: http://legislaturautuado.com/res/1-2016-2017.pdf

最后,我下载了包含以下几行的文档:

from pathlib import Path
filename = Path('first.pdf')
pdfurl = 'http://legislaturautuado.com/res/1-2016-2017.pdf'
response = requests.get(pdfurl)
filename.write_bytes(response.content)

我看过几篇关于类似主题的帖子,但其中大多数已经有了指向 pdf 文档的链接。就我而言,我需要获取 pdf 文档的链接才能下载它。如果有任何建议可以帮助我将所有内容放在一个过程中,我将不胜感激。

标签: pythonpandasbeautifulsoup

解决方案


只需使用df您已经拥有的。遍历该列中的项目,获取pdfs 的源 url 并保存它们。

就是这样:

import requests
from bs4 import BeautifulSoup
import pandas as pd

page = requests.get("http://legislaturautuado.com/pgs/resolutions.php?st=5&f=2016").text
html_table = BeautifulSoup(page, "html.parser").find("table")

df = pd.read_html(str(html_table), header=0)[0]
df["Link"] = [link.get("href") for link in html_table.find_all("a")]

for link in df["Link"]:
    response = requests.get(link, "html.parser").text
    pdf_object = BeautifulSoup(response, "html.parser").find("object")
    pdf_url, _ = pdf_object["data"].split("#")
    print(f"Fetching {pdf_url}")
    with open(f"{pdf_url.rpartition('/')[-1]}", "wb") as f:
        f.write(requests.get(pdf_url).content)

这应该为您提供所有 pdf 文件。


推荐阅读