清除HTML保留自定义标记

2024-03-28 20:50:15 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一根像下面这样的线。你知道吗

<GPE>LUSAKA</GPE> (<ORG>AP</ORG>) -- X&Y Ltd. &amp; M.K. Ltd will be merged.

如何使它成为有效的XMLetree.XMLParser语法分析器不抛出错误。我需要把它转换成类似的东西。你知道吗

<GPE>LUSAKA</GPE> (<ORG>AP</ORG>) -- X&amp;Y Ltd. &amp; M.K. Ltd will be merged.

为此,我尝试使用tidylib。但它删除了所有的自定义标签。看到代码了吗

options = {
    'wrap': 0,
    'indent': 0,
    'output-xhtml': 1,
    'numeric-entities': 1
}
html, warnings = tidylib.tidy_fragment(data, options)

输出为

LUSAKA (AP) -- X&amp;Y Ltd. &amp; M.K. Ltd will be merged.

Tags: org错误标签bemergedwilloptionsamp
1条回答
网友
1楼 · 发布于 2024-03-28 20:50:15
>>> from lxml import etree
>>> tree = etree.fromstring('<GPE>LUSAKA</GPE> (<ORG>AP</ORG>)   X&Y Ltd. &amp; M.K. Ltd will be merged.', etree.HTMLParser())
>>> etree.tostring(tree)
'<html><body><gpe>LUSAKA</gpe> (<org>AP</org>)   X&amp;Y Ltd. &amp; M.K. Ltd will be merged.</body></html>'
>>> tree.xpath('//gpe/text()')
['LUSAKA']

相关问题 更多 >