如何使用lxml.html text_content()或等效文件将<br>保留为换行符?

2024-05-20 00:00:49 发布

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

我想在从lxml元素提取文本内容时将<br>标记保留为\n

示例代码:

fragment = '<div>This is a text node.<br/>This is another text node.<br/><br/><span>And a child element.</span><span>Another child,<br> with two text nodes</span></div>'

h = lxml.html.fromstring(fragment)

输出:

> h.text_content()
'This is a text node.This is another text node.And a child element.Another child, with two text nodes'

Tags: andtextbrdivnodechildiswith