You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用BeautifulSoup删除h1标签内class为brand的div元素

解决方法

你的代码出错是因为对BeautifulSoup的API用法有误:extract()方法本身就会直接将对应元素从父节点的DOM结构中移除,不需要额外调用replace方法,且你对Tag对象直接使用replace的写法不符合API规范。

正确实现代码如下:

# 定位h1节点
h1 = item_detail_soup.find("h1")
# 定位h1下class为brand的div节点,存在则直接移除
brand_div = h1.find("div", class_="brand")
if brand_div:
    brand_div.extract()
# 替换全角中括号为半角,匹配预期输出格式
output = str(h1).replace("〔NEW〕", "(NEW)")
print(output)

运行后即可得到你预期的输出结果:

<h1> (NEW) iPhone12 256GB </h1>

内容的提问来源于stack exchange,提问作者Abu Sayed

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.28 08:24:03