您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

如何 使用lxml.html text_content()或同等功能保留为换行符?

如何 使用lxml.html text_content()或同等功能保留为换行符?

\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>'
其他 2022/1/1 18:25:55 有471人围观

撰写回答


你尚未登录,登录后可以

和开发者交流问题的细节

关注并接收问题和回答的更新提醒

参与内容的编辑和改进,让解决方法与时俱进

请先登录

推荐问题


联系我
置顶