How to tell python HTMLParser to stop

I have an example of using when a tag link, and its attributes rel=dns-prefetch, and then just say that dns is allowed.

I made a flag like that pre_resolve_dns_enabledand set it to true as follows.

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.

Any help?

+1
source share
1 answer

HTMLParser is not meant to stop. For this you want to use a streaming parser, for example xml.saxor xml.etree.cElementTree.

Is it really a problem to digest the whole HTML file? The expected use case is as follows:

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

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

If this is really a problem, you can break the HTML input into pieces and pass them until you find your tag, for example:

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
+2
source

All Articles