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

ext*_*mpo 16 python lxml lxml.html

我想保留<br>标签,就像\n从lxml元素中提取文本内容一样.

示例代码:

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)
Run Code Online (Sandbox Code Playgroud)

输出:

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

bob*_*nja 21

\n在每个<br />元素的尾部添加一个字符应该给出你期望的结果:

>>> import lxml.html as html
>>> 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>'
>>> doc = html.document_fromstring(fragment)
>>> for br in doc.xpath("*//br"):
        br.tail = "\n" + br.tail if br.tail else "\n"

>>> doc.text_content()
'This is a text node.\nThis is another text node.\n\nAnd a child element.Another child,\n with two text nodes'
>>> 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>'
Run Code Online (Sandbox Code Playgroud)