繁体   English   中英

我该如何保存? <br> 作为lxml.html text_content()或等效的换行符?

[英]How can I preserve <br> as newlines with lxml.html text_content() or equivalent?

我想在从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'

\\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>'

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM