[英]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.