使用Python Selenium遇ValueError:无法将'[id]'转为浮点数
问题排查与解决
错误原因
- 参数传递不匹配:
wait_until_visibility_of_elements函数定义的第一个参数是locator,第二个是timeout,但调用时传入了By.CSS_SELECTOR和'[id]'两个参数,导致'[id]'被错误当作timeout参数传入,触发字符串转浮点数的异常。 - 定位器格式不符合要求:Selenium的
EC.visibility_of_any_elements_located方法要求接收元组形式的定位器(如(By.CSS_SELECTOR, '[id]')),原函数参数设计未适配这个规则。 - 原函数未返回元素列表:即使等待成功,原函数也没有返回找到的元素,会导致上层
elements变量为None,后续代码无法正常执行。
解决方法
方案1:修改函数参数定义,适配多参数传入
调整函数,让它接收定位方式、定位值和可选超时时间,再组合成Selenium要求的元组定位器,同时返回元素列表:
def wait_until_visibility_of_elements(self, by, value, timeout=None): timeout = timeout if timeout else self.default_timeout locator = (by, value) try: return WebDriverWait(self.driver, timeout).until(EC.visibility_of_any_elements_located(locator)) except TimeoutException: raise Exception(f"Element/s: {locator} not displayed after timeout of {timeout} ")
调用方式保持不变:
elements = self.sl.wait_until_visibility_of_elements(By.CSS_SELECTOR, '[id]')
方案2:调整调用方式,传入元组定位器
如果不想修改函数定义,直接将定位器作为单个元组参数传入,同时修复函数的返回逻辑:
# 调用时传入元组形式的定位器 elements = self.sl.wait_until_visibility_of_elements((By.CSS_SELECTOR, '[id]'))
修正后的函数:
def wait_until_visibility_of_elements(self, locator, timeout=None): timeout = timeout if timeout else self.default_timeout try: return WebDriverWait(self.driver, timeout).until(EC.visibility_of_any_elements_located(locator)) except TimeoutException: raise Exception(f"Element/s: {locator} not displayed after timeout of {timeout} ")
额外优化点
在identifier方法的列表推导式中,增加对元素id是否存在的判断,避免re.fullmatch因None值报错:
matching_elements = [element for element in elements if element.get_attribute("id") and re.fullmatch(pattern, element.get_attribute("id"))]
内容的提问来源于stack exchange,提问作者Wazzuper11
相关产品推荐
相关产品推荐

