HTMLParseError
from HTMLParser import HTMLParser, HTMLParseError class MyHTMLParser(HTMLParser): def handle_data(self, data): data = data.strip(" \t\r\n") if data: print 'Data: "%s"' % data def handle_starttag(self, tag, attrs): print "Encountered the biginning of a %s tag" % tag def handle_endtag(self, tag): print "Encountered the end of a %s tag" % tag def main(t_file): data = open(t_file) mp = MyHTMLParser() try: mp.feed(data.read()) except HTMLParseError, msg: print "Error Msg: %s" % msg if __name__ == "__main__": main(t_file)
from HTMLParser import HTMLParser, HTMLParseError
「HTMLParseError」を書かないとだめ
except HTMLParseError, msg:
「msg」と'msg' attributegが使えるようになる。簡単なエラー内容(brief message explaining the error)が返される。
実行すると
D:\python>python htmlparser-test.py D:\test_error.html Encountered the biginning of a html tag Encountered the biginning of a head tag Encountered the biginning of a title tag Data: "TEST HTML" Encountered the end of a title tag Encountered the biginning of a body tag Encountered the biginning of a h1 tag Data: "Test" Encountered the end of a h1 tag Encountered the biginning of a p tag Data: "worng ex" Encountered the end of a p tag Encountered the biginning of a a tag Error Msg: junk characters in start tag: '\x82\xb1\x82\xb1\x83N\x83\x8a src="http:/', at line 9, column 35
とりあえず備忘録メモ。
根本的にはわかってないので、ちゃんと調べないと。というか、この書き方は正しいのでしょうか?
参考:
13.1 HTMLParser -- Simple HTML and XHTML parser