Как сказать Python HTMLParser остановиться

1

У меня есть пример использования, когда тег 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.

Любая помощь?

Теги:
dns
html-parsing

1 ответ

2
Лучший ответ

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-код на куски и передать их, пока не найдете свой тег, например:

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

Ещё вопросы

Сообщество Overcoder
Наверх
Меню