使用 Python、Requests 和 BeautifulSoup 下載 PDF 檔案
Requests 和 BeautifulSoup 是 Python 庫,可以下載任何線上檔案或 PDF。Request 庫用於傳送 HTTP 請求並接收響應。BeautifulSoup 庫用於解析響應中接收到的 HTML 並獲取可下載的 PDF 連結。在本文中,我們將瞭解如何使用 Python 中的 Request 和 Beautiful Soup 下載 PDF 檔案。
安裝依賴項
在 Python 中使用 BeautifulSoup 和 Request 庫之前,我們需要使用 pip 命令在我們的系統中安裝這些庫。要安裝 Request 和 BeautifulSoup 庫,請在您的終端中執行以下命令。
pip install requests pip install beautifulsoup4
使用 Request 和 Beautiful Soup 下載 PDF 檔案
要從網際網路下載 PDF 檔案,您需要首先使用 Request 庫找到 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 可下載連結。
廣告