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

Python Selenium提取数值转整数求中位数出错求助

问题分析与修正方案

错误原因

  1. 列表元素添加方式错误
    原代码用y += s,当s是字符串(比如"1500")时,会把字符串的每个字符拆成单独元素加入列表,比如['1','5','0','0'],而非将整个数值作为一个元素存储。
  2. 未转换为数值类型
    处理后的s仍是字符串,statistics.median会按字符的ASCII值排序计算,而非数值大小,这就是输出2的原因(字符'2'的ASCII值在所有提取到的字符中处于中间位置)。

修正后的代码

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

prara = WebDriverWait(driver, 20).until(EC.presence_of_all_elements_located((By.CLASS_NAME, 'price-value'))) 

y = []
for j in prara:
    o = j.text.strip()  # 去除首尾空白,避免空文本或空格干扰
    if o:  # 跳过空文本元素
        s = o.replace(",", "")
        try:
            num = int(s)  # 将字符串转换为整数
            y.append(num)  # 把完整数值作为单个元素加入列表
        except ValueError:
            print(f"无法转换为整数的无效文本:{o}")

if y:  # 确保列表非空再计算中位数
    prval = statistics.median(y)
    print(prval)
else:
    print("未提取到有效数值")

关键修改说明

  • 用y.append(num)替代y += s,保证每个价格数值作为独立元素存入列表。
  • 增加int(s)转换步骤,让中位数计算基于数值大小而非字符排序。
  • 加入strip()和空值判断、异常处理,避免网页元素文本异常导致程序崩溃。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.21 16:36:20