python - 如何告诉 python HTMLParser 停止

标签 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.

有什么帮助吗?

最佳答案

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 分成 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/

相关文章:

python - Numba 和二维 numpy 数组的列表

java - Java中的非阻塞(异步)DNS解析

dns - Azure Web App自定义域和域解析

java - JSOUP 为 html 添加额外的编码内容

python - 在 python 中提取表单键值对表单 html 页面或解析 html 页面

python - 带有偏移量索引的 Pandas 单个时间戳

python - re.search() 再次调用时返回 None

python - 解决硬币上的动态规划问题

nginx - 上游服务IP变化时Kubernetes nginx刷新ip地址

python - 在Python中使用BeautifulSoup提取表标签值?