我如何保存< br>作为带有lxml.html text_content()或等效名称的换行符? [英] How can I preserve <br> as newlines with lxml.html text_content() or equivalent?

查看:77
本文介绍了我如何保存< br>作为带有lxml.html text_content()或等效名称的换行符?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I want to preserve <br> tags as \n when extracting the text content from lxml elements.

示例代码:

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'

推荐答案

在每个<br />元素的末尾添加一个\n字符应该可以得到您期望的结果:

Prepending an \n character to the tail of each <br /> element should give the result you're expecting:

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

这篇关于我如何保存&lt; br&gt;作为带有lxml.html text_content()或等效名称的换行符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆