如何使用美丽的汤提取相同类别的数据(文本)?

2024-04-26 18:08:38 发布

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

我在做一个个人项目,从网站上搜集数据。我试着用BeautifulSoup来做这个,但是我在同一个类中遇到了不同的属性。例如:

<div class="pi--secondary-price">
<span class="pi--price">$11.99 /<abbr title="Kilogram">kg</abbr></span>
<span class="pi--price">$5.44 /<abbr title="Pound">lb.</abbr></span>
</div>

我怎么才能拿到每公斤11.99美元?现在我要 11.99美元/公斤 5.44美元/磅

我已经做了x.select('.pi—二级价格'),但它同时返回两个价格。我怎么才能只得到一个价格(11.99美元/公斤)


Tags: 数据项目div属性title网站pi价格
1条回答
网友
1楼 · 发布于 2024-04-26 18:08:38

您可以首先获取<abbr>标记,然后搜索相应的父标记。像这样:

from bs4 import BeautifulSoup

html = '''
<div class="pi secondary-price">
<span class="pi price">$11.99 /<abbr title="Kilogram">kg</abbr></span>
<span class="pi price">$5.44 /<abbr title="Pound">lb.</abbr></span>
</div>
'''  

soup = BeautifulSoup(html, 'html.parser')

kg = soup.find(title="Kilogram")
print(kg.parent.text)

这将为您提供所需的输出$11.99 /kg。有关更多信息,请参阅BeautifulSoupdocumentation

相关问题 更多 >