首页 > 文章列表 > 使用Python的Requests和BeautifulSoup下载PDF文件

使用Python的Requests和BeautifulSoup下载PDF文件

Python requests beautifulsoup
376 2023-09-06

Request 和 BeautifulSoup 是可以在线下载任何文件或 PDF 的 Python 库。请求库用于发送 HTTP 请求和接收响应。 BeautifulSoup 库用于解析响应中收到的 HTML 并获取可下载的 pdf 链接。在本文中,我们将了解如何在 Python 中使用 Request 和 Beautiful Soup 下载 PDF。

安装依赖项

在 Python 中使用 BeautifulSoup 和 Request 库之前,我们需要使用 pip 命令在系统中安装这些库。要安装 request 以及 BeautifulSoup 和 Request 库,请在终端中运行以下命令。

pip install requests
pip install beautifulsoup4

使用 Request 和 Beautiful Soup 下载 PDF

要从互联网下载 PDF,您需要首先使用请求库找到 pdf 文件的 URL。然后我们可以使用 Beautiful Soup 解析 HTML 响应并提取 PDF 文件的链接。然后将基本 URL 和解析后收到的 PDF 链接结合起来,得到 PDF 文件的 URL。现在我们可以使用request方法发送Get请求来下载文件了。

示例

在下面的代码中,将包含 PDF 文件 URL 的页面的有效 URL 放在“https://example.com/document.pdf”处

import requests
from bs4 import BeautifulSoup

# Step 1: Fetch the PDF URL
url = 'https://example.com/document.pdf'
response = requests.get(url)

if response.status_code == 200:
   # Step 2: Parse the HTML to get the PDF link
   soup = BeautifulSoup(response.text, 'html.parser')
   link = soup.find('a')['href']

   # Step 3: Download the PDF
   pdf_url = url + link
   pdf_response = requests.get(pdf_url)

   if pdf_response.status_code == 200:
      with open('document.pdf', 'wb') as f:
         f.write(pdf_response.content)
      print('PDF downloaded successfully.')
   else:
      print('Error:', pdf_response.status_code)
else:
   print('Error:', response.status_code)

输出

PDF downloaded successfully.

结论

在本文中,我们讨论了如何使用 Python 中的 Request 和 Beautiful Soup 库从互联网下载 PDF 文件。通过 request 方法,我们可以发送 HTTP 请求来验证 PDF 链接。一旦找到包含 PDF 文件链接的页面,我们就可以使用 Beautiful Soup 下载解析页面并获取 PDF 可下载链接。