注意: htmllib 已在 Python 3.5 中移除 (Python 2 專用)。現代專案請使用 html.parser (標準庫)、BeautifulSoup 或 lxml。本文保留歷史參考並提供現代對應寫法。
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()
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)
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())
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)
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)}")
html.parser 無依賴。lxml。