如何告诉python HTMLParser停止

2024-03-29 12:08:17 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个用例,当一个标记是link,它的属性是rel=dns-prefetch,那么只需说预解析dns是启用的。在

我创建了一个标志pre_resolve_dns_enabled,并将其设置为true,如下所示。在

class Extractor(HTMLParser):

    def __init__(self):
        HTMLParser.__init__(self)
        self.pre_resolve_dns_enabled = False

    def feed(self, data):
        HTMLParser.feed(self,data)

    def handle_starttag(self, tag, attrs):
        if tag == 'link' and ('rel', 'dns-prefetch') in attrs:
            self.pre_resolve_dns_enabled = True
            #Now if one dns is resolved so whole domain remains resolved , how do I tell the parser to abort now , leaving the flag to true.

有什么帮助吗?在


Tags: selftruedatainitdnsdeftagfeed
1条回答
网友
1楼 · 发布于 2024-03-29 12:08:17

HTMLParser不是为停止而设计的。为此,您希望使用流式解析器,如xml.sax或{}。在

消化整个HTML文件真的是个问题吗?预期的用例如下:

extractor = Extractor()
... feed html to extractor using one or more .feed() calls ...
extractor.close()

if extractor.pre_resolved_dns_enabled:
  ...
else:
  ...

如果真的是个问题,你可以把输入的HTML分成块,然后输入直到找到你的标签,例如:

^{pr2}$

相关问题 更多 >