使用Beautifulsoup更新HTML中包含<img>标记的<p>标记中的文本

2024-10-01 00:36:05 发布

您现在位置:Python中文网/ 问答频道 /正文

我有下面的beautifulsouphtml标记,我想将标记中的文本TEXT TO BE UPDATED更新为SOMETHING ELSE。你知道吗

<p><img src="./img.jpg"> TEXT TO BE UPDATED.</p>

假设上面<p>标记的Beautifulsoup对象是p_tag。我试图使用p_tag.string.replace_with('SOMETHING ELSE'),但它不起作用,因为p_tag.string总是返回None。知道为什么吗?你知道吗


Tags: totext标记文本srcimgstringtag
1条回答
网友
1楼 · 发布于 2024-10-01 00:36:05

您需要使用p_tag.text来获取文本,使用p_tag.string来设置新文本。你知道吗

像这样:

source = '<p><img src="./img.jpg"> TEXT TO BE UPDATED.</p>'
bsoup = BeautifulSoup(source, 'html.parser')
p_tag = bsoup.p

old_text = p_tag.text
new_text = p_tag.img.text + ' Something new'
p_tag.string = new_text
print(p_tag.prettify())
#  prints `<p><img src="./img.jpg"> Something new </p>`

相关问题 更多 >