Skip to main content
 首页 » 编程设计

python之用于删除 XML 注释和 HTML 元素的 Python 中的正则表达式

2025年05月04日25zhoujg

我正在使用 Universal feed Parser 解析 RSS 内容。有时在描述标签中 我得到如下值:

<!--This is the XML comment --> 
<p>This is a Test Paragraph</p></br> 
<b>Sample Bold</b> 
<m:Table>Sampe Text</m:Table> 

为了删除 HTML 元素/标签,我使用了以下正则表达式。

pattern = re.compile(u'<\/?\w+\s*[^>]*?\/?>', re.DOTALL | re.MULTILINE | re.IGNORECASE | re.UNICODE) 
desc = pattern.sub(u" ", desc) 

这有助于删除 HTML 标记,但不会删除 xml 注释。如何同时删除元素和 XML 注释?

请您参考如下方法:

使用 lxml :

import lxml.html as LH 
 
content=''' 
<!--This is the XML comment --> 
<p>This is a Test Paragraph</p></br> 
<b>Sample Bold</b> 
<Table>Sampe Text</Table> 
''' 
 
doc=LH.fromstring(content) 
print(doc.text_content()) 

产量

This is a Test Paragraph 
Sample Bold 
Sampe Text