我有一个用例告诉我们当标签是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
or 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 分成块并提供它们,直到找到您的标签,例如:
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
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)