如何告诉python HTMLParser停止

时间:2014-12-18 05:15:28

标签: python dns html-parsing

我有一个用例告诉我,当标记为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.

任何帮助?

1 个答案:

答案 0 :(得分:3)

HTMLParser并非旨在停止。为此,您希望使用流式解析器,如xml.saxxml.etree.cElementTree

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

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

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

如果它确实存在问题,您可以将输入HTML拆分为块并提供它们直到找到您的标记,例如:

html = ...the html to parse...
chunks = [ html[i:i+1024] for i in xrange(0, len(html), 1024) ]
extractor = Extractor()
for c in chunks:
  if extractor.pre_resolved_dns_enabled:
    break
  extractor.feed(c)
extractor.close()
# check extractor.pre_resolved_dns_enabled