beautifulsoup4

Parsing

網頁抓取

概述 beautifulsoup4

BeautifulSoup4 (bs4) 是用來解析 HTML 和 XML 文件的 Python 函式庫。它從頁面原始碼建立一個解析樹,使導航、搜尋和提取資料變得容易。與 requests 函式庫結合,它構成了最常見的 Python 網路抓取堆疊的基礎。

在PyRun中,BeautifulSoup4 透過 micropip 載入並立即運作。您可以解析原始 HTML 字串、提取標籤、屬性和文字內容,並探索文件結構 - 所有這些都無需本機 Python 環境。它是安全學習網路抓取概念的絕佳工具。

程式碼和執行輸出

導航 HTML 文件並從中提取資料。

HTML Parsing with BeautifulSoup在編輯器中執行
from bs4 import BeautifulSoup

html_doc = """
<html>
  <head><title>Sample Page</title></head>
  <body>
    <h1>Article List</h1>
    <ul>
      <li><a href="/post/1" class="post">Intro to Python</a></li>
      <li><a href="/post/2" class="post">NumPy Basics</a></li>
      <li><a href="/post/3" class="post">Pandas Guide</a></li>
    </ul>
    <p class="footer">© 2025 PyRun</p>
  </body>
</html>
"""

soup = BeautifulSoup(html_doc, 'html.parser')
print("Title:", soup.title.string)
print("H1:", soup.h1.string)
print("\nLinks:")
for a in soup.find_all('a', class_='post'):
    print(f"  {a.string}  →  {a['href']}")

相關套餐

推薦的 Python 資源

透過相關的互動式教學、備忘單和程式碼比較來擴展您的知識。