Selenium获取的Web元素转整数/浮点数报错,如何解决?
解决Selenium元素文本转浮点数/整数报错问题
报错的核心原因是你获取到的元素文本为空字符串,或者文本中包含非数字/小数点的字符,导致无法直接转换为数值类型。以下是具体的解决方法:
1. 过滤空文本并清理非数字字符
先对获取到的文本做预处理,跳过空内容,同时移除干扰转换的符号:
import re prices = driver.find_elements(By.CLASS_NAME, 'a-price-whole') total_prices = [] for price_elem in prices: # 去除文本前后空白,避免空白字符串被误判 text = price_elem.text.strip() # 跳过空文本 if not text: continue # 只保留数字和小数点,移除货币符号、逗号等干扰字符 cleaned_text = re.sub(r'[^0-9.]', '', text) # 处理多个小数点的异常情况(比如"199.99.9") if cleaned_text.count('.') > 1: parts = cleaned_text.split('.') cleaned_text = parts[0] + '.' + ''.join(parts[1:]) # 尝试转换,捕获转换失败的情况 try: num = float(cleaned_text) total_prices.append(num) except ValueError: print(f"无法转换为浮点数的文本: {text}") continue
2. 等待元素文本完全渲染
有时候元素虽然被定位到,但页面还没完成渲染,导致文本为空。可以通过显式等待确保文本加载完成:
from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC import re # 先等待所有价格元素加载完成 prices = WebDriverWait(driver, 10).until( EC.presence_of_all_elements_located((By.CLASS_NAME, 'a-price-whole')) ) total_prices = [] for price_elem in prices: # 等待当前元素的文本非空,超时3秒则跳过 try: WebDriverWait(driver, 3).until( lambda d: price_elem.text.strip() != '' ) except: print("元素文本未加载,跳过当前元素") continue # 后续处理同方法1 text = price_elem.text.strip() cleaned_text = re.sub(r'[^0-9.]', '', text) if cleaned_text.count('.') > 1: parts = cleaned_text.split('.') cleaned_text = parts[0] + '.' + ''.join(parts[1:]) try: num = float(cleaned_text) total_prices.append(num) except ValueError: print(f"转换失败: {text}") continue
内容的提问来源于stack exchange,提问作者Raymond Liu
相关产品推荐
相关产品推荐

