萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> 程式語言綜合

Python htmllib 解析 HTML 內容:標準庫舊版用法與現代替代

注意: htmllib 已在 Python 3.5 中移除 (Python 2 專用)。現代專案請使用 html.parser (標準庫)、BeautifulSoup 或 lxml。本文保留歷史參考並提供現代對應寫法。

舊版 htmllib 範例 (Python 2)

import htmllib, urllib, formatter, sys

website = urllib.urlopen("https://yourweb.com")
data = website.read()
website.close()

format = formatter.AbstractFormatter(formatter.DumbWriter(sys.stdout))
parser = htmllib.HTMLParser(format)
parser.feed(data)
parser.close()

現代替代 1:html.parser (標準庫,Python 3)

from html.parser import HTMLParser
import urllib.request

class MyParser(HTMLParser):
    def handle_starttag(self, tag, attrs):
        print(f"Start tag: {tag}, attrs: {attrs}")
    def handle_data(self, data):
        if data.strip():
            print(f"Data: {data.strip()}")

with urllib.request.urlopen('https://example.com') as resp:
    html = resp.read().decode('utf-8', errors='replace')

parser = MyParser()
parser.feed(html)

現代替代 2:BeautifulSoup 4 (推薦,功能最強)

pip install beautifulsoup4 lxml

from bs4 import BeautifulSoup
import urllib.request

with urllib.request.urlopen('https://example.com') as resp:
    html = resp.read()

soup = BeautifulSoup(html, 'lxml')

# 提取所有連結
for link in soup.find_all('a', href=True):
    print(link['href'], link.get_text(strip=True))

# 提取標題
print(soup.title.string)

# CSS 選擇器
for item in soup.select('div.content > p'):
    print(item.get_text())

現代替代 3:lxml (高效能)

pip install lxml
from lxml import html
import urllib.request

with urllib.request.urlopen('https://example.com') as resp:
    tree = html.fromstring(resp.read())

for link in tree.xpath('//a/@href'):
    print(link)

提取所有超鏈接完整範例 (BeautifulSoup)

from bs4 import BeautifulSoup
import urllib.request

url = 'https://httpbin.org/html'
with urllib.request.urlopen(url) as resp:
    soup = BeautifulSoup(resp.read(), 'html.parser')

print(f"Page title: {soup.title.string if soup.title else 'None'}")
print("\nAll links:")
for a in soup.find_all('a', href=True):
    print(f"  {a['href']} -> {a.get_text(strip=True)}")

總結建議

  • Python 3 專案勿使用 htmllib (已移除)。
  • 簡單需求:標準庫 html.parser 無依賴。
  • 複雜選擇、容錯、CSS/xpath:BeautifulSoup + lxml 為行業標準。
  • 高效能大量解析:直接用 lxml。
copyright © 萬盛學電腦網 all rights reserved