python 2.x 的 HTMLParser 在 python 3.x 用法不一樣。
python2 的 code 直接 run 會有error:
ImportError: No module named 'HTMLParser'
如果使用 pip3 install HTMLParser 會有下面的新 error:
No module named 'htmlentitydefs'
或
No module named 'markupbase'
Python 3,需要使用下面的 import 而不是使用 pip3 上的版本:
import html.parser
python 3 HTMLParser 教學:
https://docs.python.org/3/library/html.parser.html
from html.parser import HTMLParser
class MyHTMLParser(HTMLParser):
def handle_starttag(self, tag, attrs):
print("Encountered a start tag:", tag)
def handle_endtag(self, tag):
print("Encountered an end tag :", tag)
def handle_data(self, data):
print("Encountered some data :", data)
parser = MyHTMLParser()
parser.feed('<html><head><title>Test</title></head>'
'<body><h1>Parse me!</h1></body></html>')