代码之家  ›  专栏  ›  技术社区  ›  user3525290

靓汤取代<;

  •  2
  • user3525290  · 技术社区  · 7 年前

    我找到了要替换的文本,但打印时 soup 格式更改。 <div id="content">stuff here</div> 变成 &lt;div id="content"&gt;stuff here&lt;/div&gt; . 如何保存数据?我试过了 print(soup.encode(formatter="none"))

    from bs4 import BeautifulSoup
    
    with open(index_file) as fp:
        soup = BeautifulSoup(fp,"html.parser")
    
    found = soup.find("div", {"id": "content"})
    found.replace_with(data)
    

    当我打印时 found ,我得到了正确的格式:

    >>> print(found)
    <div id="content">stuff</div>
    

    index_file 内容如下:

     <!DOCTYPE html>
     <head>
        Apples 
     </head>
     <body>
    
       <div id="page">
        This is the Id of the page
    
      <div id="main">
    
         <div id="content">
           stuff here
         </div>
      </div>
     footer should go here
     </div>
    </body>
    </html>
    
    1 回复  |  直到 7 年前
        1
  •  4
  •   Mad Physicist    7 年前

    这个 found 对象不是Python字符串,而是 Tag

    type(found)
    

    A 标签 NavigableString . NavigableString公司 很像字符串,但它只能包含进入HTML内容部分的内容。

    found.replace_with('<div id="content">stuff here</div>')
    

    你在问 标签 被替换为 包含文字的。HTML能够显示该字符串的唯一方法是转义所有的尖括号,就像它所做的那样。

    你可能不想弄得一团糟,而是想保住你的饭碗

    found.string.replace_with('stuff here')
    

    请注意,正确的替换不会试图覆盖标记。

    当你这么做的时候 found.replace_with(...) 建立 在父层次结构中被替换。但是,这个名字 建立 一直指向与以前相同的过期对象。这就是为什么印刷 soup 显示更新,但正在打印 建立 没有。