如何使用 Python 爬取段落?


可以使用 Python 的 Beautiful Soup 庫來爬取段落。BeautifulSoup 是一個 Python 庫,可以輕鬆解析 HTML 和 XML 文件。它提供了一種方便的方式來瀏覽和搜尋已解析的資料,使其成為 Web 爬取任務的理想選擇。透過利用其強大的功能,我們可以從網頁中提取特定的元素,例如段落。在這篇文章中,我們將使用 Python 的 Beautiful Soup 庫來爬取段落。

安裝所需的庫

在爬取段落之前,我們需要安裝必要的庫。開啟您的終端或命令提示符,並執行以下命令來安裝 BeautifulSoup 和 requests(一個用於發出 HTTP 請求的庫)

pip install beautifulsoup4 requests

從網站爬取段落

我們將從 openAI 網站開始爬取段落。我們將使用 requests 庫來獲取頁面的 HTML 內容,然後使用 BeautifulSoup 來解析和提取所需的段落。

演算法

  • 匯入必要的庫:requests 和 BeautifulSoup。

  • 定義您要爬取的網站的 URL。

  • 使用 requests.get() 函式向網站傳送 GET 請求並存儲響應。

  • 使用 BeautifulSoup 透過建立具有響應文字和指定為“html.parser”的解析器型別的 BeautifulSoup 物件來解析 HTML 內容。

  • 使用 BeautifulSoup 物件的 find_all() 方法找到頁面上的所有段落元素,並將“p”作為引數傳遞。

  • 遍歷段落並使用 text 屬性列印其文字。

示例

import requests
from bs4 import BeautifulSoup

# URL of the website to scrape
url = "https://openai.com/"

# Send a GET request to the website
response = requests.get(url)

# Parse the HTML content using BeautifulSoup
soup = BeautifulSoup(response.text, "html.parser")

# Find all the paragraph elements
paragraphs = soup.find_all("p")

# Iterate over the paragraphs and print their text
for paragraph in paragraphs:
    print(paragraph.text)

輸出

Our work to create safe and beneficial AI requires a deep understanding of the potential risks and benefits, as well as careful consideration of the impact.
We research generative models and how to align them with human values.
Our API platform offers our latest models and guides for safety best practices.
Developing safe and beneficial AI requires people from a wide range of disciplines and backgrounds.
I encourage my team to keep learning. Ideas in different topics or fields can often inspire new ideas and broaden the potential solution space.

處理不同的 HTML 結構

網頁可能有不同的 HTML 結構,段落可能位於各種標籤或類屬性內。為了處理這種情況,我們可以相應地修改我們的程式碼。

示例

讓我們考慮一個段落包含在具有特定類的 <div> 標籤中的示例。在這個例子中,我們在 html 變數中定義了一個 HTML 結構。我們透過傳遞 HTML 內容並指定解析器為“html.parser”來建立一個 BeautifulSoup 物件 soup。然後我們使用 soup.find() 定位具有類名“content”的父元素。接下來,我們使用 find_all() 查詢父元素中的所有段落元素。

最後,我們遍歷段落並列印它們的文字。

from bs4 import BeautifulSoup

html = '''
<html>
  <body>
    <div class="content">
      <h1>Website Title</h1>
      <p>This is the first paragraph.</p>
      <div class="inner-div">
        <p>This is the second paragraph.</p>
      </div>
      <p>This is the third paragraph.</p>
    </div>
  </body>
</html>
'''

soup = BeautifulSoup(html, "html.parser")

# Find the parent element containing the paragraphs
parent_element = soup.find("div", class_="content")

# Find all the paragraph elements within the parent element
paragraphs = parent_element.find_all("p")

for paragraph in paragraphs:
    print(paragraph.text)

輸出

This is the first paragraph.
This is the second paragraph.
This is the third paragraph.

處理巢狀元素

有時,網頁中的段落可能包含巢狀元素,例如連結、影像或跨度。如果我們只想提取段落的純文字,我們可以使用 BeautifulSoup 提供的 get_text() 方法。

示例

讓我們考慮一個例子,在這個例子中,我們在程式碼本身中定義了一個 HTML 結構,我們需要提取包含連結等巢狀元素的段落。

在下面的示例中,我們在 HTML 變數中定義了一個 HTML 結構。我們透過傳遞 HTML 內容並指定解析器為“html.parser”來建立一個 BeautifulSoup 物件 soup。然後我們使用 soup.find() 定位具有類名“content”的父元素。接下來,我們使用 find_all() 查詢父元素中的所有段落元素。

對於每個段落,我們使用 get_text() 僅提取純文字,不包括任何巢狀元素(如連結)。最後,我們列印提取的文字。

from bs4 import BeautifulSoup

html = '''
<html>
  <body>
    <div class="content">
      <h1>Website Title</h1>
      <p>This is the first paragraph.</p>
      <p>This is the second paragraph with a <a href="https://example.com">link</a> in it.</p>
      <p>This is the third paragraph.</p>
    </div>
  </body>
</html>
'''

soup = BeautifulSoup(html, "html.parser")

# Find the parent element containing the paragraphs
parent_element = soup.find("div", class_="content")

# Find all the paragraph elements within the parent element
paragraphs = parent_element.find_all("p")

for paragraph in paragraphs:
    # Extract only the plain text, excluding any nested elements
    text = paragraph.get_text()
    print(text)

輸出

This is the first paragraph.
This is the second paragraph with a link in it.
This is the third paragraph.

結論

在本文中,我們討論瞭如何在不同情況下使用 Python 從 HTML 頁面中抓取段落。我們還探討了在從 HTML 提取段落時處理不同的 HTML 結構和處理巢狀元素的情況。現在我們可以應用 Web 抓取技術來收集來自網站的有價值資訊,用於分析、研究或其他目的。

更新於:2023年10月13日

720 次瀏覽

開啟您的職業生涯

完成課程獲得認證

開始學習
廣告
© . All rights reserved.