首页 > 解决方案 > html解析器忽略特定标签,如链接和列表

问题描述

我可能不理解 html 解析器的正确性,因为我想知道如何保持特定标签与我的最终文本中的一样,比如链接标签。

在这里,我需要解析 p 和 strong 标签,并希望 a 标签相同。但以下内容只是返回链接文本。

from html.parser import HTMLParser

class _HTMLToText(HTMLParser):
    def __init__(self):
        HTMLParser.__init__(self)
        self._buf = []
        self.hide_output = False
    def handle_starttag(self, tag, attrs):
        if tag in ('p', 'br') and not self.hide_output:
            self._buf.append('\n')
        elif tag in ('script', 'style'):
            self.hide_output = True
        elif tag == 'strong':
            self._buf.append('<b>')
        elif tag == 'a':
            self.hide_output = True
    def handle_startendtag(self, tag, attrs):
        if tag == 'br':
            self._buf.append('\n')

    def handle_endtag(self, tag):
        if tag == 'p':
            self._buf.append('\n')
        elif tag in ('script', 'style'):
            self.hide_output = False
        elif tag == 'strong':
            self._buf.append('</b>')
        elif tag == 'a':
            self.hide_output = False
    def handle_data(self, text):
        if text and not self.hide_output:
            self._buf.append(re.sub(r'\s+', ' ', text))
        elif text and self.hide_output:
            self._buf.append(text)
    def handle_entityref(self, name):
        if name in name2codepoint and not self.hide_output:
            c = chr(name2codepoint[name])
            self._buf.append(c)
    def handle_charref(self, name):
        if not self.hide_output:
            n = int(name[1:], 16) if name.startswith('x') else int(name)
            self._buf.append(chr(n))
    def get_text(self):
        return re.sub(r' +', ' ', ''.join(self._buf))



parser = _HTMLToText()
parser.feed('<p>More infos you find here <a class="link" href="https://www.duckduckgo.com">duckduck</a>.</p>')
parser.close()
print("parser", parser.get_text().strip()) ## ->parser More infos you find here duckduck.

但所需的输出应该是:

parser More infos you find here <a class="link" href="https://www.duckduckgo.com">duckduck</a>

标签: python

解决方案


推荐阅读