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

Selenium获取的带单位温度文本如何转为int类型用于数值比较

问题原因

你收到ValueError报错的核心原因是:通过temperature.text获取到的文本包含温度单位、空格等非数字字符(比如示例里的9 ℃就包含空格和℃符号),无法直接传入float()方法做转换。

解决方案

优先推荐用正则表达式提取文本中的数字部分,兼容性更强,不管单位是c还是℃、数字和单位之间有没有空格都可以正常匹配:

import re
from selenium.webdriver.common.by import By

# 定位温度元素
temperature_ele = driver.find_element(By.ID, "temperature")
# 匹配文本中的数字(支持整数、小数格式)
temp_res = re.search(r"\d+\.?\d*", temperature_ele.text)
if not temp_res:
    # 未匹配到数字的异常处理,可根据业务调整
    raise ValueError("温度元素未识别到有效数值")
# 转换为int类型
temperature = int(float(temp_res.group()))

# 后续业务逻辑
if temperature < 19:
    driver.find_element(By.LINK_TEXT, 'Buy sunscreens').click()
elif temperature > 34:
    driver.find_element(By.LINK_TEXT, 'Buy moisturizers').click()

如果可以确定温度文本的格式固定是「数字+空格+单位」,也可以用更简单的字符串分割方法:

temp_text = temperature_ele.text.strip()
# 按空格拆分后取第一个元素就是纯数字部分
temp_num = temp_text.split()[0]
temperature = int(float(temp_num))
额外提示

你当前的判断逻辑可能存在业务错误:通常温度更高时需要买防晒霜,温度更低时需要买保湿霜,可根据实际需求核对条件是否写反。
另外原代码中find_element_by_link_text是Selenium3的过时写法,Selenium4+推荐统一用find_element(By.LINK_TEXT, 文本)的写法,避免运行时出现弃用警告。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.29 16:15:01