【问题标题】:<> becomes &lt &gt in beautifulsoup<> 在 beautifulsoup 中变成 &lt &gt
【发布时间】:2020-04-24 18:21:39
【问题描述】:

假设我有项目divdiv 是一个 beautifulsoup 对象(由 findAll 获得)。源代码如下:

<div>text1 <span>text2</span></div>

我想要做的是用 text3 替换 text1。我试过了:

  1. div.string.replace_with(newstr), where newstr="text3 &lt;span&gt;text2&lt;/span&gt;" 这不起作用,因为 div.string 是 None

  2. div.replace_with(newstr)
    这不起作用,因为当我将 html 代码保存到文件中时,最终结果显示&amp;lt&amp;gt 而不是“”。

【问题讨论】:

  • 您使用的是哪个解析器?尝试使用 lxml
  • 你的意思是初始化时Beautifulsoup(...,features='lxml')中的特征属性。我已经这样做了。

标签: python beautifulsoup


【解决方案1】:

你可以找到div标签然后找到next_element这是text1然后replace_withtext3

from bs4 import BeautifulSoup

html= '''<div>text1 <span>text2</span></div>'''
soup = BeautifulSoup(html, 'lxml')
soup.find('div').next_element.replace_with('text3')
print(soup)

【讨论】:

    【解决方案2】:

    只是玩交互式提示...我确信有更好的解决方案但是...

    from bs4 import BeautifulSoup
    
    data = '''<div>text1 <span>text2</span></div>'''
    soup = BeautifulSoup(data, features="lxml")
    div = soup.find('div')
    a, *b = div.contents
    c = a.replace('text1', 'text3')
    a.replace_with(c)
    print(div)
    

    【讨论】:

      猜你喜欢
      • 2014-01-23
      • 1970-01-01
      • 2018-12-24
      • 2017-02-08
      • 2015-08-26
      • 2010-11-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多