TypeError报错咨询:WebElement与float无法比较的问题排查
问题分析与解决
错误原因
代码的elif分支里误用了WebElement对象price_printBarthemlowaBear和float值BarthemlowaBear做比较,而非转换后的价格变量price_printofBarthemlowaBear。其他商品价格低于阈值时,会触发if分支,不会执行到elif,因此没暴露问题;当前商品价格高于阈值,走到elif就抛出类型错误。
修复后的代码
BarthemlowaBear = float(21.95) def barthembear(): driver.get(urlJellycatBarthemlowBear) time.sleep(1) name_ofBarthemlowaBear = driver.find_element(By.CLASS_NAME, "base") price_printBarthemlowaBear = driver.find_element(By.CLASS_NAME, "price") print(name_ofBarthemlowaBear.text) time.sleep(1) print(price_printBarthemlowaBear.text) price_printofBarthemlowaBear = float(price_printBarthemlowaBear.text.replace('£','')) if price_printofBarthemlowaBear < BarthemlowaBear: print("****************BUY***********************") elif price_printofBarthemlowaBear > BarthemlowaBear: print("!!!!!!!!!!!!!!!!!!do not buy!!!!!!!!!!!!!!!!!")
额外优化建议
- 替换
time.sleep为显式等待,避免页面加载慢导致元素获取失败:from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC # 替换time.sleep(1)为: WebDriverWait(driver, 10).until(EC.visibility_of_element_located((By.CLASS_NAME, "price"))) - 增加价格转换的异常处理,避免文本格式异常报错:
try: price_printofBarthemlowaBear = float(price_printBarthemlowaBear.text.replace('£','')) except ValueError: print("价格格式解析失败") return - 处理元素找不到的情况,添加异常捕获:
from selenium.common.exceptions import NoSuchElementException try: name_ofBarthemlowaBear = driver.find_element(By.CLASS_NAME, "base") price_printBarthemlowaBear = driver.find_element(By.CLASS_NAME, "price") except NoSuchElementException: print("无法获取商品名称或价格元素") return
内容的提问来源于stack exchange,提问作者atryingcoder
相关产品推荐
相关产品推荐

