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

Python-Selenium WebDriver循环求和返回零致断言失败求助

问题排查与解决

核心问题分析

求和结果始终为0,大概率是以下两种情况:

  1. prices 列表为空,循环根本没执行
  2. 提取的文本包含非数字字符(比如货币符号₹),但未做处理(不过这种情况会直接报错,所以更可能是第一种)

分步解决

1. 修复定位器,排除表头干扰

购物车页面的表头行也是<tr>,但只有商品行带cart-item类,原定位器会匹配到表头的空元素,或者根本没命中商品行。修改定位器:

prices = driver.find_elements(By.CSS_SELECTOR, "tr.cart-item td:nth-child(5) p")

2. 添加等待,确保元素加载完成

页面可能还没渲染完毕就执行了元素查找,导致prices为空。用显式等待替代直接查找:

from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

# 等待最多10秒,直到所有商品小计元素加载完成
wait = WebDriverWait(driver, 10)
prices = wait.until(EC.presence_of_all_elements_located((By.CSS_SELECTOR, "tr.cart-item td:nth-child(5) p")))

3. 处理货币符号,避免转换错误

提取的文本带有₹符号,直接转int会报错,需要先去除符号:

total_sum = 0  # 不要用sum当变量名,会覆盖Python内置函数
for price in prices:
    # 打印文本确认内容,方便排查
    print(f"当前提取的价格文本:{price.text}")
    # 去掉货币符号后转整数
    total_sum += int(price.text.replace('₹', ''))

4. 修正总金额的提取逻辑

总金额元素的文本同样带有₹,也要处理后再转整数:

total_amount_text = driver.find_element(By.CLASS_NAME, "totAmt").text
totalAmount = int(total_amount_text.replace('₹', ''))

完整修正代码

from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

# 等待商品小计元素加载
wait = WebDriverWait(driver, 10)
prices = wait.until(EC.presence_of_all_elements_located((By.CSS_SELECTOR, "tr.cart-item td:nth-child(5) p")))

total_sum = 0
for price in prices:
    price_str = price.text.replace('₹', '')
    total_sum += int(price_str)
    
print(f"计算的总和:{total_sum}")

# 提取并处理总金额
total_amount_text = driver.find_element(By.CLASS_NAME, "totAmt").text
totalAmount = int(total_amount_text.replace('₹', ''))
print(f"页面显示的总金额:{totalAmount}")

assert total_sum == totalAmount

额外排查步骤

如果问题仍存在,先执行以下代码确认元素是否存在:

print(f"找到的价格元素数量:{len(prices)}")

如果输出为0,说明定位器仍不正确,右键检查页面上的小计元素,复制正确的CSS选择器或XPath。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.12 20:23:14