如何在 Python 中解析本地 HTML 檔案?


在處理網頁抓取、資料分析和自動化時,使用 Python 解析本地 HTML 檔案是一項常見任務。

在這篇文章中,我們將學習如何在 Python 中解析本地 HTML 檔案。我們將探索使用 Python 從 HTML 檔案中提取資料的各種技術。我們將涵蓋修改和刪除檔案中的元素、列印資料、使用遞迴子生成器遍歷檔案結構、查詢標籤子元素,甚至透過從給定連結中提取資訊來進行網頁抓取。透過程式碼示例和語法,我們將演示如何利用 BeautifulSoup 和 lxml 等 Python 庫來高效地完成這些任務。

設定環境

在深入解析 HTML 檔案之前,讓我們確保我們的 Python 環境已安裝必要的庫。我們將主要依賴兩個流行的庫:BeautifulSoup 和 lxml。要安裝它們,請使用以下 pip 命令

pip install beautifulsoup4
pip install lxml

安裝完成後,我們就可以開始解析本地 HTML 檔案並提取資料了。我們可以使用多種技術,例如修改檔案、遍歷 HTML 結構、網頁抓取等。讓我們詳細瞭解其中的一些技術,並附帶語法和完整的示例

載入和修改 HTML 檔案

要解析 HTML 檔案,我們需要將其載入到我們的 Python 指令碼中。我們可以使用內建的 open 函式開啟檔案,然後讀取其內容來實現這一點。以下是一個示例

語法

with open('example.html', 'r') as file:
    html_content = file.read()

載入 HTML 檔案後,我們可以使用字串操作技術或 BeautifulSoup 等庫提供的更高階方法來修改其內容。例如,要從 HTML 檔案中刪除特定元素,我們可以使用 BeautifulSoup 的 extract 方法

輸入 HTML 檔案

#myhtml.html

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>
<body>
  <div class="my-class">
      Hello World
  </div>
</body>
</html>

示例

在這個示例中,我們載入了 HTML 檔案('myhtml.html'),建立了一個 BeautifulSoup 物件,使用其標籤和屬性找到了要刪除的元素,最後將其從 HTML 結構中刪除。可以使用 prettify 方法列印修改後的 HTML,以視覺化更改。

from bs4 import BeautifulSoup

# Load the HTML file
with open('myhtml.html', 'r') as file:
    html_content = file.read()

# Create a BeautifulSoup object
soup = BeautifulSoup(html_content, 'lxml')

# Find the element to remove by its tag and remove it
element_to_remove = soup.find('div', {'class': 'my-class'})
element_to_remove.extract()

# Print the modified HTML
print(soup.prettify())

輸出

<!DOCTYPE html>
<html lang="en">
 <head>
  <meta charset="utf-8"/>
  <meta content="IE=edge" http-equiv="X-UA-Compatible"/>
  <meta content="width=device-width, initial-scale=1.0" name="viewport"/>
  <title>
   Document
  </title>
 </head>
 <body>
 </body>
</html>

從 HTML 檔案中提取資料

列印或從 HTML 檔案中提取特定資料涉及到導航其結構。BeautifulSoup 提供了一系列方法來完成此操作。要提取資料,我們通常需要使用其標籤、類或屬性找到所需的元素或元素。

例如,讓我們考慮一個包含以下結構的文章列表的 HTML 檔案

示例

在這個示例中,我們載入了 HTML 檔案,建立了一個 BeautifulSoup 物件,找到了 ul 元素,然後提取了其中的所有 li 元素。最後,我們列印了每個 li 元素的文字內容,它代表文章標題。

HTML

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>
<body>
  <div class="">
      <ul>
        <li>Article 1</li>
        <li>Article 2</li>
        <li>Article 3</li>
      </ul>
  </div>
</body>
</html>

Python

from bs4 import BeautifulSoup

# Load the HTML file
with open('myhtml.html', 'r') as file:
    html_content = file.read()

# Create a BeautifulSoup object
soup = BeautifulSoup(html_content, 'lxml')

# Find all li elements within the ul tag
articles = soup.find('ul').find_all('li')

# Print the article titles
for article in articles:
    print(article.text)

輸出

Article 1
Article 2
Article 3

使用遞迴子生成器遍歷 HTML 結構

遞迴子生成器是遍歷 HTML 檔案結構的強大技術。BeautifulSoup 允許我們使用 .children 屬性迭代標籤的子元素。我們可以遞迴遍歷整個結構以提取所需的資訊。

示例

在這個示例中,我們載入了 HTML 檔案,建立了一個 BeautifulSoup 物件,定義了一個遞迴函式 traverse_tags,並使用根元素(在本例中為 soup 物件)呼叫它。該函式列印標籤名稱及其內容,然後遞迴地為每個子元素呼叫自身。

HTML

myhtml.html

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>
<body>
  <div class="container">
    <h1>Welcome to Tutorialspoint</h1>
    <p>Arrays </p>
    <p>Linkedin List</p>
 </div>
</body>
</html>

Python

from bs4 import BeautifulSoup

# Load the HTML file
with open('myhtml.html', 'r') as file:
    html_content = file.read()
# Create a BeautifulSoup object
soup = BeautifulSoup(html_content, 'lxml')

# Define a recursive function to traverse the structure
def traverse_tags(element):
    print(element.name)
    print(element.text)
    for child in element.children:
        if child.name:
            traverse_tags(child)

# Traverse the HTML structure
traverse_tags(soup)

輸出

[document]


Document


Welcome to Tutorialspoint
Arrays 
Linkedin List


html



Document

Welcome to Tutorialspoint
Arrays 
Linkedin List

head

Document
meta
meta
meta
title
Document
body

Welcome to Tutorialspoint
Arrays 
Linkedin List

div
Welcome to Tutorialspoint
Arrays 
Linkedin List
h1
Welcome to Tutorialspoint
p
Arrays 
p
Linkedin List

從連結中進行網頁抓取

除了解析本地 HTML 檔案外,我們還可以透過抓取網頁來提取有用的資訊。使用 BeautifulSoup 和 requests 等 Python 庫,我們可以獲取網頁的 HTML 內容並提取相關資料。

語法

# Define the URL
url = 'https://tutorialspoint.tw/index.htm'
# Send a GET request
response = requests.get(url)
# Create a BeautifulSoup object with the webpage content
soup = BeautifulSoup(response.content, 'lxml')

示例

在這個示例中,我們使用 requests 庫向所需的網頁傳送了一個 GET 請求。然後,我們使用響應內容建立了一個 BeautifulSoup 物件,並使用適當的標籤提取了文章標題和描述。最後,我們列印了提取的資訊。

import requests
from bs4 import BeautifulSoup

# Define the URL of the webpage to scrape
url = 'https://tutorialspoint.tw/index.htm'

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

# Check if the request was successful (status code 200)
if response.status_code == 200:
    print("Fetch was successful.")
    
    # Create a BeautifulSoup object with the webpage content
    soup = BeautifulSoup(response.content, 'lxml')
    
    # Find and print the title of the webpage
    mytitle = soup.find('title').text
    print(f"HTMl Webpage Title: {mytitle}")
    
    # Find and print the first paragraph of the content
    myparagraph = soup.find('p').text
    print(f"First Paragraph listed in the website: {myparagraph}")
    
else:
    print(f"Error code: {response.status_code}")

輸出

Fetch was successful.
HTMl Webpage Title: Online Courses and eBooks Library | Tutorialspoint
First Paragraph listed in the website: Premium Courses

結論

使用 Python 解析本地 HTML 檔案為資料提取和操作提供了廣泛的可能性。透過修改檔案、刪除元素、列印資料、利用遞迴子生成器以及從連結中進行網頁抓取,我們可以有效地從 HTML 檔案中提取相關資訊。Python 利用 BeautifulSoup 和 lxml 等強大的庫來導航和操作 HTML 結構。有了本文中的知識和程式碼示例,您現在可以自信地在 Python 專案中提取和使用 HTML 檔案中的資料了。

更新於: 2023年8月31日

3K+ 閱讀量

開啟您的 職業生涯

透過完成課程獲得認證

立即開始
廣告