【问题标题】:Modifying a BeautifulSoup .string with line breaks用换行符修改 BeautifulSoup .string
【发布时间】:2015-02-07 18:38:04
【问题描述】:

我正在尝试使用 BeautifulSoup 更改 html 文件的内容。此内容将来自基于 python 的文本,因此它将有 \n 换行符...

newContent = """This is my content \n with a line break."""
newContent = newContent.replace("\n", "<br>")
htmlFile.find_all("div", "product").p.string = newContent

当我这样做时,html 文件 &lt;p&gt; 文本更改为:

This is my content &lt;br&gt; with a line break.

如何更改 BeautifulSoup 对象中的字符串并保持&lt;br&gt; 中断?如果字符串只包含\n,那么它将创建一个实际的换行符。

【问题讨论】:

    标签: python html beautifulsoup


    【解决方案1】:

    您需要创建单独的元素; &lt;p&gt; 标记中包含的不是一个 文本,而是一系列文本和&lt;br/&gt; 元素。

    不要用文本&lt;br/&gt;(将被转义)替换\n换行符,而是在换行符上分割文本并在其间插入额外的元素:

    parent = htmlFile.find_all("div", "product")[0].p
    lines = newContent.splitlines()
    parent.append(htmlFile.new_string(lines[0]))
    for line in lines[1:]:
        parent.append(htmlFile.new_tag('br'))
        parent.append(htmlFile.new_string(line))
    

    这使用Element.append() method 将新元素添加到树中,并使用BeautifulSoup.new_string() and BeautifulSoup.new_tag() 创建这些额外元素。

    演示:

    >>> from bs4 import BeautifulSoup
    >>> htmlFile = BeautifulSoup('<p></p>')
    >>> newContent = """This is my content \n with a line break."""
    >>> parent = htmlFile.p
    >>> lines = newContent.splitlines()
    >>> parent.append(htmlFile.new_string(lines[0]))
    >>> for line in lines[1:]:
    ...     parent.append(htmlFile.new_tag('br'))
    ...     parent.append(htmlFile.new_string(line))
    ... 
    >>> print htmlFile.prettify()
    <html>
     <head>
     </head>
     <body>
      <p>
       This is my content
       <br/>
       with a line break.
      </p>
     </body>
    </html>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-12-24
      • 1970-01-01
      • 1970-01-01
      • 2020-01-05
      • 2022-07-07
      相关资源
      最近更新 更多