gpt4 book ai didi

python - <> 在 beautifulsoup 中变成 < >

转载 作者:行者123 更新时间:2023-12-01 06:36:50 27 4
gpt4 key购买 nike

假设我有项目 div , div是一个 beautifulsoup 对象(通过 findAll 获得)。来源如下:

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

我想要做的是将text1替换为text3。我尝试过:

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

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

最佳答案

你可以找到div标签,然后找到next_element,即text1,然后找到replace_with text3

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)

关于python - <> 在 beautifulsoup 中变成 &lt &gt,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59625116/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com