如何使用BeautifulSoup提取嵌套HTML



我需要使用BeautifulSoup为下面的HTML代码提取价格。

<div class="price-original">
<span class="product-price-amount">
<span class="notranslate"> £899.89</span>
</span>
<div>

我无法使用下面的代码,因为在网页上有几个价格实例使用相同的html语法。

price1 = soup.find('div', class_='price-original').find('span', class_="notranslate").text.strip().replace("£","").replace(",","")
print('Price:', price1)

由于这个原因,我需要一种方法来提取基于所有3个html元素,因为这会产生一个唯一的html实例。

粗略地看一下这个网站,看起来你感兴趣的价格(即页面上主要产品的最终价格)是在一个不同的html中,基于产品是否打折。

假设您的soup确实包含此信息,对于折扣产品,请尝试使用

soup.select_one('div.product-price-container span.you-pay-value')

对于未打折的产品,请尝试:

soup.select_one('div.product-price-container span.product-price-amount > span.notranslate')

你可以直接使用

soup.find('span', class_ = 'notranslate').string

而不是逐一遍历div>span>span树。
这将给你' £899.89',你可以设置你喜欢的格式。

最新更新