python - 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>
解决方案
推荐阅读
- raspberry-pi - 包“git”的文件列表文件包含空文件名错误
- amazon-web-services - 如何在 Elastic Beanstalk 单实例环境中将 HTTP 重定向到 HTTPS
- c# - 无法打破 C# 中的无限 While 循环
- python - 在 python 中制作视频的顺序播放列表
- mysql - 错误:MySQL 意外关闭这可能是由于端口阻塞,缺少依赖项
- database - 在代码中使用 DynamoDB 过滤器表达式或过滤器哪个更好?
- javascript - 变量未在 vue 函数中定义
- reactjs - Typescript 和 styled-components 在导入时出错
- javascript - 关于使用 JavaScript Function 构造函数作为沙箱的问题
- wix - msi 日志文件状态不反映安装文件状态