You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何通过BeautifulSoup提取cost-box下price元素的数值?

提取price元素内的数值方案

你已经成功定位到cost-box容器,以下是几种提取<price>标签内10.00数值的实用方法:

方法1:精准定位price标签

从已获取的container对象中直接查找<price>标签,再提取文本内容:

# 从cost-box容器中找到price标签
price_tag = container.find('price')
# 获取标签文本并去除多余空白
price_value = price_tag.get_text(strip=True)
print(price_value)  # 输出结果:10.00

方法2:链式简化写法

如果页面结构稳定,也可以直接从soup对象链式定位,省去单独存储container的步骤:

price_value = soup.find('div', class_='cost-box').find('price').get_text(strip=True)
print(price_value)

方法3:容错处理版本

为避免标签不存在引发报错,可以增加判断逻辑,让代码更健壮:

if container:
    price_tag = container.find('price')
    if price_tag:
        price_value = price_tag.get_text(strip=True)
        print(price_value)
    else:
        print("未找到price标签")
else:
    print("未找到cost-box容器")

内容的提问来源于stack exchange,提问作者DC37

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.11 15:40:02