[HOME]: [Mac OS X]: [MacPython]: [Emacs]: [生存報告記]:

HTMLParser_Python

目次

概要

HTMLを処理するライブラリ。Saxのようにイベントドリブンによる処理となる。

利用方法

#!python
file = file("/Users/sakito/python/htmlparse/sample.html")

import htmllib, formatter

class MyHTMLParser(htmllib.HTMLParser):
    def start_html(self, attr):
        """start_{tag}"""
        pass

    def end_html(self):
        """end_{tag}"""
        pass

    def do_br(self, attr):
        """do_{tag}は<br>のような終了タグが必要ないタグに用いる."""
        pass

    def start_p(self, attr):
        """<p> tag"""
        print attr

    def handle_data(self, text):
        """This is called everytime we get to text data (ie. not tags) """
        print "Get text: %s" % text


if __name__ == '__main__':
    p = MyHTMLParser(formatter.AbstractFormatter(formatter.NullWriter()))
    p.feed(file.read())
    p.close()
    #print file.read()

参考サイト

http://aspn.activestate.com/ASPN/Mail/Message/python-Tutor/1176140


CategoryPython