【问题标题】:Python keeping newlines in lxml.html after cssselect and text_content()Python 在 cssselect 和 text_content() 之后在 lxml.html 中保留换行符
【发布时间】:2011-05-13 15:57:19
【问题描述】:

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

例如,下面会去掉

标签并加入行,这不是我想要的:
body = doc.cssselect("div.body")[0]
content = body.text_content()

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

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

【问题讨论】:

    标签: python newline html-parsing lxml


    【解决方案1】:

    根据文档,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
    

    【讨论】:

    • 谢谢,这就是我最终做的:paragraphs = self.doc.cssselect('div#body p') paragraph_text = [paragraph.text_content() for paragraph in paragraphs] content = '\ n\n'.join(paragraph_text)
    • body.xpath("*//p") 对我不起作用,我将其更改为 body.xpath("./p")。无论如何都要 +1
    • 另见stackoverflow.com/questions/18660382/…,它的替代效果更好。
    猜你喜欢
    • 2013-09-10
    • 2013-01-08
    • 2011-05-20
    • 2013-07-27
    • 2013-11-10
    • 2015-08-16
    • 2012-11-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多