我已经尝试了使用BeautifulSoup解析html的以下代码。
item_detail_soup = BeautifulSoup(html, "html.parser")
h1 = item_detail_soup.find("h1")我的H1解析器输出是:
<h1>
<div class="brand" style="display: block; font-size: 0.75rem;">Apple(#34567)</div>
〔NEW〕 iPhone12 256GB </h1>我正在尝试删除这个类名为brand的div。
我想要的输出:
<h1> (NEW) iPhone12 256GB </h1>我尝试过使用extract(),然后使用replace,但是失败了。
h1 = item_detail_soup.find("h1")
h1 = h1.replace(item_detail_soup.find("h1").div.extract(),'')我怎样才能得到我想要的输出?
发布于 2021-10-31 12:19:11
好消息是,你走在了正确的道路上--为了达到你的目标,你也可以使用.extract(),.replace_with()和.decompose()。
提取和分解有什么不同?
.extract()从树中删除标记或字符串,并将其作为附加解析树返回/保留,而decompose()则从树中删除标记并完全销毁它及其内容。
哪里出了问题?
不会得到预期结果的原因是,您试图对h1变量进行操作,使其始终为空(.decompose())或包含提取的tag (.extract())。
如何修复?
首先选择要从树中删除的tag,删除它,然后选择您的<h1>查看结果。
示例(在item_detail_soup中只有一个带有类品牌的div )
from bs4 import BeautifulSoup
html = '''<h1><div class="brand" style="display: block; font-size: 0.75rem;">Apple(#34567)</div>〔NEW〕 iPhone12 256GB </h1>'''
item_detail_soup = BeautifulSoup(html, 'html.parser')
item_detail_soup.select_one('div.brand').extract()
h1 = item_detail_soup.find('h1')示例(item_detail_soup中有多个带有类品牌的div )
请注意,您一次只能使用一个选项,所以我将其他选项注释掉了。
from bs4 import BeautifulSoup
html = '''<h1><div class="brand" style="display: block; font-size: 0.75rem;">Apple(#34567)</div>〔NEW〕 iPhone12 256GB </h1>'''
item_detail_soup = BeautifulSoup(html, 'lxml')
for item in item_detail_soup.select('div.brand'):
item.extract()
#item.decompose()
#item.replace_with('')
item_detail_soup.h1输出
<h1>〔NEW〕 iPhone12 256GB </h1>发布于 2021-10-31 10:57:22
尝尝这个
item_detail_soup = BeautifulSoup(html, "html.parser")
for div in item_detail_soup .find_all("div", {'class':'brand'}):
div.decompose()
h1 = item_detail_soup.find("h1")https://stackoverflow.com/questions/69786116
复制相似问题