Python HTML解析器

3
我正在使用HTMLParser解析HTML文档,我想要打印出p标签开始和结束之间的内容。以下是我的代码片段:
    def handle_starttag(self, tag, attrs):
        if tag == 'p':
            print "TODO: print the contents"
3个回答

7

根据@tauran发布的内容,您可能想要做以下操作:

from HTMLParser import HTMLParser

class MyHTMLParser(HTMLParser):
    def print_p_contents(self, html):
        self.tag_stack = []
        self.feed(html)

    def handle_starttag(self, tag, attrs):
        self.tag_stack.append(tag.lower())

    def handle_endtag(self, tag):
        self.tag_stack.pop()

    def handle_data(self, data):
        if self.tag_stack[-1] == 'p':
            print data

p = MyHTMLParser()
p.print_p_contents('<p>test</p>')

现在,您可能希望将所有<p>内容推入一个列表中并将其作为结果返回,或者其他类似的操作。
今天我学到了:当使用这样的库时,您需要考虑堆栈!

1
你忘记调用 feed 方法了,而列表使用的方法是 append 而非 push - tauran
在一个大的HTML文件中,我得到了一个if self.tag_stack[-1] == 'p': IndexError: list index out of range的错误。 - Matthieu Riegler
@MatthieuRiegler,听起来你的tag_stack是空的? - Daren Thomas
@MatthieuRiegler,请检查并将代码编辑为:if len(self.tag_stack) and self.tag_stack[-1] == 'p': - Daren Thomas
请记住,HTML不是XML。特别是,开始和结束标签不需要匹配。例如'<ul> <li>text </ul>'(但不一定有'</li>')。因此,堆栈弹出可能需要继续直到找到匹配项。但即使如此,对于格式不正确的序列(如'<b><i>text</b></i>'),这也不足够。 - Rhubbarb
根据handle_starttag方法的文档,tag参数是标签的名称,转换为小写字母。不需要调用tag.lower()。 - frogcoder

5

我为文档中的示例进行了扩展:

from HTMLParser import HTMLParser

class MyHTMLParser(HTMLParser):

    def handle_starttag(self, tag, attrs):
        print "Encountered the beginning of a %s tag" % tag

    def handle_endtag(self, tag):
        print "Encountered the end of a %s tag" % tag

    def handle_data(self, data):
        print "Encountered data %s" % data

p = MyHTMLParser()
p.feed('<p>test</p>')

-

Encountered the beginning of a p tag
Encountered data test
Encountered the end of a p tag

不错的使用方法:http://docs.python.org/library/htmlparser.html#example-html-parser-application - Fredrik Pihl

1
它似乎对我的代码没有用,所以我将tag_stack = []定义在外面,就像一种全局变量。
from html.parser import HTMLParser
    tag_stack = []
    class MONanalyseur(HTMLParser):

    def handle_starttag(self, tag, attrs):
        tag_stack.append(tag.lower())
    def handle_endtag(self, tag):
        tag_stack.pop()
    def handle_data(self, data):
        if tag_stack[-1] == 'head':
            print(data)

parser=MONanalyseur()
parser.feed()    

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接