HTML unescape 不适用于 BeautifulSoup Replace_with

问题描述 投票:0回答:1

我正在尝试使用 BeautifulSoup 编辑 Python 中某些元素的内部 HTML。这是一个简单的例子:

from bs4 import BeautifulSoup
import html

html_str = '<div><span><strong>Hello world</strong></span></div>'
soup = BeautifulSoup(html_str, 'html.parser')
span = soup.select_one('span')
span.replace_with('message: ' + html.unescape(span.decode_contents()) + ', end of message')

print(soup)

我期望得到一个解码后的字符串,例如:

<div>message: <strong>Hello world</strong>, end of message</div>

但我得到的是:

<div>message: &lt;strong&gt;Hello world&lt;/strong&gt;, end of message</div>

请注意,此行为仅在目标元素包含子元素时发生,例如如果您尝试在强元素上执行此代码(带有

soup.select_one('strong')
),它会按预期工作。

python beautifulsoup
1个回答
0
投票

最简单的方法是将

.replace_with
与新的
BeautifulSoup
对象一起使用,例如:

from bs4 import BeautifulSoup

html_str = "<div><span><strong>Hello world</strong></span></div>"
soup = BeautifulSoup(html_str, "html.parser")

span = soup.select_one("span")
span.replace_with(BeautifulSoup(f"message: {str(span)}, end of message", "html.parser"))

print(soup)

打印:

<div>message: <span><strong>Hello world</strong></span>, end of message</div>
© www.soinside.com 2019 - 2024. All rights reserved.