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

如何用BeautifulSoup提取span.product__price末尾的价格文本?

解决方案:提取product__price标签中的价格文本

针对span标签内包含隐藏调试div、仅需提取末尾价格文本的问题,提供三种动态处理方案:

方案1:筛选带价格标识的文本节点

通过获取所有文本节点,过滤掉空白内容后,提取以$开头的价格字符串:

response = requests.get(url, auth=('user', 'pass')).text
soup = bs(response, 'html.parser')
for price_span in soup.find_all(class_='product__price'):
    # 提取所有非空白文本节点
    text_nodes = [node.strip() for node in price_span.find_all(text=True) if node.strip()]
    # 筛选价格(假设价格以$开头)
    price = next((node for node in text_nodes if node.startswith('$')), None)
    if price:
        print(price)

方案2:移除隐藏div后提取文本

先定位并删除隐藏的调试div,再提取剩余文本内容:

response = requests.get(url, auth=('user', 'pass')).text
soup = bs(response, 'html.parser')
for price_span in soup.find_all(class_='product__price'):
    # 找到隐藏div并移除
    hidden_div = price_span.find('div', hidden=True)
    if hidden_div:
        hidden_div.decompose()
    # 提取并清理文本
    price = price_span.get_text(strip=True)
    print(price)

方案3:直接定位末尾文本节点

利用价格位于span标签末尾文本节点的特性,直接提取最后一个非空白文本:

response = requests.get(url, auth=('user', 'pass')).text
soup = bs(response, 'html.parser')
for price_span in soup.find_all(class_='product__price'):
    # 筛选出所有纯文本类型的非空白节点
    text_nodes = [node.strip() for node in price_span.contents if isinstance(node, str) and node.strip()]
    if text_nodes:
        # 取最后一个节点即为价格
        price = text_nodes[-1]
        print(price)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.12 04:42:01