บทนำ
โมดูล html.parser มีคลาส HTMLParser สำหรับแยกวิเคราะห์ (parse) HTML สามารถจับ tag เริ่มต้น tag สิ้นสุด และข้อมูลระหว่าง tag ได้
ตัวอย่าง HTML ตัวอย่าง
<html> <head> <title>Welcome to Tutorials Point!</title> </head> <body> <h1>Learn anything!</h1> </body> </html>
สร้าง Custom Parser
from html.parser import HTMLParser
import io
class MyHTMLParser(HTMLParser):
def handle_starttag(self, tag, attrs):
print(f"Start tag: {tag} at {self.getpos()}")
if attrs:
print(f" Attributes: {attrs}")
def handle_endtag(self, tag):
print(f"End tag: {tag} at {self.getpos()}")
def handle_data(self, data):
if data.strip():
print(f"Data: {data.strip()} at {self.getpos()}")
parser = MyHTMLParser()
with open("test.html", "r") as f:
parser.feed(f.read())
ผลลัพธ์ตัวอย่าง
Start tag: html at (1, 0) Start tag: head at (2, 0) Start tag: title at (3, 0) Data: Welcome to Tutorials Point! at (3, 7) End tag: title at (3, 34) End tag: head at (4, 0) Start tag: body at (5, 0) Start tag: h1 at (6, 0) Data: Learn anything! at (6, 4) End tag: h1 at (6, 20) End tag: body at (7, 0) End tag: html at (8, 0)
เมธอดสำคัญอื่นๆ
handle_comment(data): คอมเมนต์ <!-- ... -->handle_entityref(name): entity เช่น &handle_charref(name): character reference เช่น Ӓgetpos(): คืน (line, offset)