在Selenium Python中如何将文本转为整数?代码失效求解
解决价格字符串转整数失败的问题
你的代码
Products = (driver.find_element(By.XPATH, '//*[@id="products"]')) Product_price = Products.find_elements(By.CSS_SELECTOR,"div[class='product unlocked enabled'] div[class='content'] span[class='price']") Product_names = Products.find_elements(By.CSS_SELECTOR,"div[class='product unlocked enabled']") for items in range (len(Product_price)): Prices[(Product_names[items].get_attribute("id"))] = Product_price[items].text
问题核心
直接用int(Product_price[items].text)转换价格时失效,本质是价格文本包含非数字内容,或者本身是小数格式,导致int()转换抛出异常中断程序。
常见原因
- 价格带货币符号(如
¥99、$199)、千位分隔符(如1,299)或空格 - 价格是小数形式(如
29.99),直接转int会触发ValueError - 部分元素文本为空或无效字符
解决方法
1. 清理价格文本,提取纯数字
先用正则去掉非数字(和小数点,若需保留小数)的内容,再转换:
import re Products = driver.find_element(By.XPATH, '//*[@id="products"]') Product_price = Products.find_elements(By.CSS_SELECTOR,"div[class='product unlocked enabled'] div[class='content'] span[class='price']") Product_names = Products.find_elements(By.CSS_SELECTOR,"div[class='product unlocked enabled']") for items in range(len(Product_price)): price_text = Product_price[items].text.strip() # 移除所有非数字和小数点的字符 clean_price_str = re.sub(r'[^\d.]', '', price_text) if clean_price_str: # 确保清理后不为空 try: # 先转float再转int(处理小数价格取整),如果要保留小数直接用float() Prices[Product_names[items].get_attribute("id")] = int(float(clean_price_str)) except ValueError: # 转换失败时设为None或记录异常,避免程序中断 Prices[Product_names[items].get_attribute("id")] = None else: Prices[Product_names[items].get_attribute("id")] = None
2. 先排查原始文本内容
如果不确定问题出在哪,可以先打印原始价格文本,定位具体异常项:
for items in range(len(Product_price)): price_text = Product_price[items].text.strip() print(f"产品ID: {Product_names[items].get_attribute('id')}, 原始价格: '{price_text}'")
根据打印结果针对性调整清理规则(比如如果只有人民币符号,直接用price_text.replace('¥', '')更高效)。
3. 用异常捕获保证程序健壮性
即使做了文本清理,仍可能有特殊情况,用try-except包裹转换逻辑,确保循环不会因单个异常项终止。
内容的提问来源于stack exchange,提问作者LearinPython103
相关产品推荐
相关产品推荐

