」工欲善其事,必先利其器。「—孔子《論語.錄靈公》
首頁 > 程式設計 > 如何使用 Beautiful Soup 從公共網路中提取數據

如何使用 Beautiful Soup 從公共網路中提取數據

發佈於2024-08-01
瀏覽:190

How Beautiful Soup is used to extract data out of the Public Web

Beautiful Soup 是用於從網頁擷取資料的 Python 函式庫。它會建立用於解析 HTML 和 XML 文件的解析樹,從而可以輕鬆提取所需的資訊。

Beautiful Soup 為網頁擷取提供了幾個關鍵功能:

  1. 導航解析樹:您可以輕鬆導航解析樹並蒐索元素、標籤和屬性。
  2. 修改解析樹:它允許您修改解析樹,包括新增、刪除和更新標籤和屬性。
  3. 輸出格式:可以將解析樹轉換回字串,方便保存修改後的內容。

要使用 Beautiful Soup,您需要安裝該程式庫以及解析器,例如 lxml 或 html.parser。您可以使用 pip
安裝它們

#Install Beautiful Soup using pip.
pip install beautifulsoup4 lxml

處理分頁

當處理跨多個頁面顯示內容的網站時,處理分頁對於抓取所有資料至關重要。

  1. 識別分頁結構:檢查網站以了解分頁的結構(例如,下一頁按鈕或編號連結)。
  2. 迭代頁面:使用循環迭代每個頁面並抓取資料。
  3. 更新URL或參數:修改URL或參數以取得下一頁的內容。
import requests
from bs4 import BeautifulSoup

base_url = 'https://example-blog.com/page/'
page_number = 1
all_titles = []

while True:
    # Construct the URL for the current page
    url = f'{base_url}{page_number}'
    response = requests.get(url)
    soup = BeautifulSoup(response.content, 'html.parser')

    # Find all article titles on the current page
    titles = soup.find_all('h2', class_='article-title')
    if not titles:
        break  # Exit the loop if no titles are found (end of pagination)

    # Extract and store the titles
    for title in titles:
        all_titles.append(title.get_text())

    # Move to the next page
    page_number  = 1

# Print all collected titles
for title in all_titles:
    print(title)

提取嵌套數據

有時,您需要提取的資料嵌套在多層標籤中。以下是如何處理嵌套資料提取。

  1. 導覽至父標籤: 尋找包含嵌套資料的父標籤。
  2. 提取嵌套標籤: 在每個父標籤中,尋找並提取嵌套標籤。
  3. 迭代嵌套標籤:迭代嵌套標籤以提取所需資訊。
import requests
from bs4 import BeautifulSoup

url = 'https://example-blog.com/post/123'
response = requests.get(url)
soup = BeautifulSoup(response.content, 'html.parser')

# Find the comments section
comments_section = soup.find('div', class_='comments')

# Extract individual comments
comments = comments_section.find_all('div', class_='comment')

for comment in comments:
    # Extract author and content from each comment
    author = comment.find('span', class_='author').get_text()
    content = comment.find('p', class_='content').get_text()
    print(f'Author: {author}\nContent: {content}\n')

處理 AJAX 請求

許多現代網站使用 AJAX 動態載入資料。處理 AJAX 需要不同的技術,例如使用瀏覽器開發人員工具監視網路請求並在抓取工具中複製這些請求。

import requests
from bs4 import BeautifulSoup

# URL to the API endpoint providing the AJAX data
ajax_url = 'https://example.com/api/data?page=1'
response = requests.get(ajax_url)
data = response.json()

# Extract and print data from the JSON response
for item in data['results']:
    print(item['field1'], item['field2'])

網頁抓取的風險

網路抓取需要仔細考慮法律、技術和道德風險。透過實施適當的保護措施,您可以減輕這些風險並負責任且有效地進行網路抓取。

  • 違反服務條款:許多網站在其服務條款 (ToS) 中明確禁止抓取。違反這些條款可能會導致法律訴訟。
  • 智慧財產權問題:未經許可抓取內容可能侵害智慧財產權,引發法律糾紛。
  • IP 封鎖:網站可能會偵測並封鎖表現出抓取行為的 IP 位址。
  • 帳號封鎖:如果在需要使用者驗證的網站上進行抓取,則用於抓取的帳號可能會被封鎖。

Beautiful Soup 是一個功能強大的庫,它透過提供易於使用的介面來導航和搜尋 HTML 和 XML 文檔,從而簡化了網頁抓取過程。它可以處理各種解析任務,使其成為任何想要從網路中提取資料的人的必備工具。

版本聲明 本文轉載於:https://dev.to/marcosconci/how-beautiful-soup-is-used-to-extract-data-out-of-the-public-web-51gg?1如有侵犯,請聯絡study_golang @163.com刪除
最新教學 更多>

免責聲明: 提供的所有資源部分來自互聯網,如果有侵犯您的版權或其他權益,請說明詳細緣由並提供版權或權益證明然後發到郵箱:[email protected] 我們會在第一時間內為您處理。

Copyright© 2022 湘ICP备2022001581号-3