Python在cssselect和text_content()之后在lxml.html中保留换行符

发布于 2024-10-03 07:58:48 字数 364 浏览 1 评论 0原文

在python中,使用lxml.html时如何保留段落(即保留换行符)?

例如,以下内容将剥离

标签并加入行,这不是我想要的:

body = doc.cssselect("div.body")[0]
content = body.text_content()

这是我尝试过但不起作用的方法:

  • lxml.html.clean.clean_html:
    • 不会保留换行符。
  • 内容.replace(" "*3,"\n\n"):
    • 无法始终如一地工作,因为 组合文本不具有相同的 空格数。

In python, How do I preserve paragraphs (i.e. keep newlines) when using lxml.html?

For example, the following will strip <p></p> tags and join the lines, which is not what I want:

body = doc.cssselect("div.body")[0]
content = body.text_content()

Here's what I've tried that doesn't work:

  • lxml.html.clean.clean_html:
    • Won't preserve the newlines.
  • content.replace(" "*3,"\n\n"):
    • Doesn't work consistently, because
      combined text does not have the same
      number of spaces.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

守望孤独 2024-10-10 07:58:48

lxml text_content 正在做根据文档应该做的事情,它正在剥离 html 标签并留下文本。

您可以通过在输出内容之前添加自己的换行符来解决此问题。

body = doc.cssselect("div.body")[0]
for para in body.xpath("*//p"):
    para.text = "\n%s\n" % para.text
content = body.text_content()
print content

The lxml text_content is doing what is supposed to according to the docs, it is stripping the html tags and leaving the text behind.

You can fix this up by adding your own newlines before outputting the content.

body = doc.cssselect("div.body")[0]
for para in body.xpath("*//p"):
    para.text = "\n%s\n" % para.text
content = body.text_content()
print content
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文