針對Python regular expression我試着用HTMLParser
實現一個HTML解析器:在使用Python的HTMLParser有效
import HTMLParser
class ExtractHeadings(HTMLParser.HTMLParser):
def __init__(self):
HTMLParser.HTMLParser.__init__(self)
self.text = None
self.headings = []
def is_relevant(self, tagname):
return tagname == 'h1' or tagname == 'h2'
def handle_starttag(self, tag, attrs):
if self.is_relevant(tag):
self.in_heading = True
self.text = ''
def handle_endtag(self, tag):
if self.is_relevant(tag):
self.headings += [self.text]
self.text = None
def handle_data(self, data):
if self.text != None:
self.text += data
def handle_charref(self, name):
if self.text != None:
if name[0] == 'x':
self.text += chr(int(name[1:], 16))
else:
self.text += chr(int(name))
def handle_entityref(self, name):
if self.text != None:
print 'TODO: entity %s' % name
def extract_headings(text):
parser = ExtractHeadings()
parser.feed(text)
return parser.headings
print extract_headings('abdk3<h1>The content we need</h1>aaaaabbb<h2>The content we need2</h2>')
print extract_headings('before<h1>Hello</h1>after')
這樣做,我想知道,如果這個模塊的API是壞的,或者如果我沒有注意到一些重要的的東西。我的問題是:
- 爲什麼我的執行
handle_charref
必須是那麼複雜?我本來期望一個好的API將代碼點作爲參數傳遞,而不是x6c
或72
作爲字符串。 - 爲什麼
handle_charref
的默認實現不會使用適當的字符串調用handle_data
? - 爲什麼沒有實用的
handle_entityref
實現我可以打電話?它可以被命名爲handle_entityref_HTML4
,它將查找HTML 4中定義的實體,然後在其上調用handle_data
。
如果提供了該API,編寫自定義HTML解析器會容易得多。那麼我的誤解在哪裏?
如果您閱讀上一個問題的答案,爲什麼不使用BeautifulSoup? HTML解析器可以解析常規無聊的HTML,但是這與實際上可以使用正則表達式處理的相同的HTML(因爲它實際上是常規的)。它不處理高級功能或任何不符合要求的內容,而BeautifulSoup具有非常好的API。 – 2010-11-15 08:45:27