我有一个用例,当标签是 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.
有什么帮助吗?
最佳答案
HTMLParser 不是为停止而设计的。为此,您需要使用像 xml.sax
或 xml.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 分成 block 并提供它们,直到找到您的标签,例如:
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
关于python - 如何告诉 python HTMLParser 停止,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27539659/