首页 > 解决方案 > Python - 使用 handle_starttag 和 handle_endtag 处理 htmlparser 数据

问题描述

我正在尝试handle_data根据给定的限制来控制handle_starttagendtag但是,我无法实现这一点。

我还使用了设置为TrueFalse实现此目的的标志,但没有对数据和标签进行控制。

这是我的代码:

class MyHTMLParser(HTMLParser):

    def __init__(self):
        HTMLParser.__init__(self)
        self.htmlList = []
        self.flag = False

    def handle_starttag(self,tag,attrs):

        if  tag.lower() in ['a','title'] and tag.lower() != 'script':
            self.flag = True

    def handle_data(self, data):

        if self.flag == True:
            words = data.split()
            for i in words:
                if i.isalpha() ==  True:  
                    self.htmlList.append(i)
            return (self.htmlList)

标签: pythonhtml-parsing

解决方案


推荐阅读