如何使用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
相关产品推荐
相关产品推荐

