美丽汤:仅解析一个元素

5

我总是遇到难题,但感觉我在这里很接近了。

正在收集的HTML块:

div class="details">
   <div class="price">
   <h3>From</h3>
   <strike data-round="true" data-currency="USD" data-price="148.00" title="US$148 ">136</strike>
   <span data-round="true" data-currency="USD" data-price="136.00" title="US$136 ">125</span>
</div>

我希望能够单独解析出“US$136”数值(span data)。以下是我的逻辑,可以捕获“span data”和“strike-data”:
我想要单独提取“US$136”这个数值(span data)。目前我的思路是捕获“span data”和“strike-data”两者:
price = item.find_all("div", {"class": "price"})
        price_final = (price[0].text.strip()[8:])
        print(price_final)

任何反馈都受到欢迎 :)
1个回答

5

price在您的情况下是一个ResultSet - 一组具有price类的div标签。现在你需要定位每个结果中的span标签(假设有多个价格要匹配):

prices = item.find_all("div", {"class": "price"})
for price in prices:
    price_final = price.span.text.strip()
    print(price_final)

如果您只需要找到一个价格:

soup.find("div", {"class": "price"}).span.get_text()

或者使用CSS选择器
soup.select_one("div.details div.price span").get_text()

请注意,如果要使用 select_one() 方法,需要安装最新的 beautifulsoup4 包:
pip install --upgrade beautifulsoup4

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接