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

Python网页爬取问题:Laughs网站椰子价格提取错误(显示0.0而非95.0)

问题解决:Laughs网站椰子价格爬取错误

问题根源

  1. 请求未携带User-Agent:你定义了user_agent但未在requests.get中使用,部分网站会拦截无UA标识的请求,返回异常页面内容,导致提取的价格值不符合预期。
  2. 字符串处理未做清理:直接替换"Rs."后转浮点数,若原始文本包含空格或无效字符,可能引发转换异常。

修复后的代码(comparison.py)

import requests
import json
from bs4 import BeautifulSoup

# 模拟Mozilla浏览器
user_agent = {'User-agent': 'Mozilla/5.0'}

def compare_prices(laughs_coconut, glomark_coconut):
    # 获取网页内容,携带User-Agent
    laughs_response = requests.get(laughs_coconut, headers=user_agent)
    glomark_response = requests.get(glomark_coconut, headers=user_agent)

    # 提取Laughs网站价格
    soup_laughs = BeautifulSoup(laughs_response.text, 'html.parser')
    price_laughs = soup_laughs.find('span', {'class': 'price'}).text
    
    # 提取Glomark网站价格
    soup_glomark = BeautifulSoup(glomark_response.text, 'html.parser')
    script_glomark = soup_glomark.find('script', {'type': 'application/ld+json'}).text
    data_glomark = json.loads(script_glomark)
    price_glomark = data_glomark['offers'][0]['price']

    # 解析价格为浮点数,增加清理步骤
    price_laughs = price_laughs.replace("Rs.", "").strip()  # 去除Rs.标识和多余空格
    price_laughs = float(price_laughs)
    price_glomark = float(price_glomark)
    
    print('Laughs   COCONUT - Item#mr-2058 Rs.: ', price_laughs)
    print('Glomark  Coconut Rs.: ', price_glomark)
    
    # 价格比较逻辑
    if price_laughs > price_glomark:
        print('Glomark is cheaper Rs.:', price_laughs - price_glomark)
    elif price_laughs < price_glomark:
        print('Laughs is cheaper Rs.:', price_glomark - price_laughs)    
    else:
        print('Price is the same')

额外调试建议

如果修复后仍有问题,可在提取price_laughs后添加打印语句,查看原始文本内容:

print("原始价格文本:", price_laughs)

这能帮你确认是否定位到了正确的元素,以及文本内容是否符合预期。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.03 21:45:38