โมดูล html.parser ให้ HTMLParser class สำหรับ parse HTML/XHTML แบบ event-driven (SAX-style)
การใช้งานพื้นฐาน
from html.parser import HTMLParser
class MyParser(HTMLParser):
def handle_starttag(self, tag, attrs):
print(f"Start tag: {tag}")
for attr in attrs:
print(f" attr: {attr}")
def handle_endtag(self, tag):
print(f"End tag: {tag}")
def handle_data(self, data):
if data.strip():
print(f"Data: {data}")
def handle_comment(self, data):
print(f"Comment: {data}")
def handle_startendtag(self, tag, attrs):
print(f"Self-closing tag: {tag}")
parser = MyParser()
parser.feed('Link')
# Start tag: a
# attr: ('href', 'https://example.com')
# Data: Link
# End tag: a
Handler Methods
| Method | Trigger | Arguments |
|---|---|---|
handle_starttag(tag, attrs) | Opening tag <tag> | tag (lowercase), attrs (list of tuples) |
handle_endtag(tag) | Closing tag </tag> | tag (lowercase) |
handle_startendtag(tag, attrs) | Self-closing <tag/> | tag, attrs |
handle_data(data) | Text content | data string |
handle_comment(data) | Comment <!--...--> | data string |
handle_entityref(name) | Named entity &name; | name |
handle_charref(name) | Numeric entity &#nnn; | name |
handle_decl(decl) | DOCTYPE <!DOCTYPE...> | decl string |
handle_pi(data) | Processing instruction <?...> | data |
ตัวอย่าง Parse HTML Document
html = '''
Tutorialspoint
Python standard library
HTML module
'''
parser = MyParser()
parser.feed(html)
# Start tag: html
# Start tag: body
# Start tag: h1
# Data: Tutorialspoint
# End tag: h1
# Start tag: b
# Data: Python standard library
# End tag: b
# Start tag: p
# Data: HTML module
# End tag: p
# Comment: This is a comment
# End tag: body
# End tag: html
Utility Methods
>> parser.get_starttag_text() # text ของ start tag ล่าสุด
''
>>> parser.getpos() # (line_number, offset)
(8, 4)
ข้อจำกัด
- ไม่ validate HTML (lenient parser)
- ไม่สร้าง DOM tree (ใช้
html.parserแบบ streaming) - สำหรับ DOM ใช้
BeautifulSoup(external) หรือxml.etree.ElementTree(XML) - Malformed HTML อาจ parse ผิดพลาด
Use Cases
- Extract links, metadata จาก HTML
- Simple scraping tasks
- HTML sanitization/cleaning
- Template processing