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

Selenium扩展模块Python TypeError问题:参数应为数值而非元组

问题:Selenium自定义函数触发TypeError,其余函数正常运行

问题场景

自定义Selenium扩展类中,wait_and_input_text函数可正常工作,但wait_until_visibility_of_element函数抛出TypeError,提示无法将元组转换为float。

正常运行的函数代码

class SeleniumExtended:
    def __init__(self, driver):
        self.driver = driver
        self.default_timeout = 10

    def wait_and_input_text(self, locator, text, timeout=None):
        timeout = timeout if timeout else self.default_timeout
        WebDriverWait(self.driver, timeout).until(
            EC.visibility_of_element_located(locator)
        ).send_keys(text)

报错的函数代码

def wait_until_visibility_of_element(self, locator, timeout=None):
    timeout = timeout if timeout else self.default_timeout
    WebDriverWait(self.driver, timeout).until(EC.visibility_of_element_located(locator))

错误信息

timeout = ('css selector', 'body > header > div > div > div.main-nav__logo > a > img')
    def wait_until_visibility_of_element(self, locator, timeout=None):
        timeout= timeout if timeout else self.default_timeout
>       WebDriverWait(self.driver, float(timeout)).until(EC.visibility_of_element_located(locator))
E       TypeError: float() argument must be a string or a real number, not 'tuple'
..\src\SeleniumExtended.py:26: TypeError
FAILED test_shawbrook_expriments.py::Test_shawex::test_shawmr - TypeError: float() argument must be a string or a real number, not 'tuple'

问题原因与解决办法

原因

调用wait_until_visibility_of_element时参数传递错误:将定位器(locator)元组误传给了timeout参数,导致timeout被赋值为元组类型,触发float转换失败。

解决办法

  1. 修正调用参数顺序:
    函数定义中参数顺序为locator在前、timeout在后,调用时需遵循该顺序:

    # 使用默认超时
    sel_ext.wait_until_visibility_of_element(('css selector', 'body > header > div > div > div.main-nav__logo > a > img'))
    # 指定自定义超时
    sel_ext.wait_until_visibility_of_element(('css selector', 'body > header > div > div > div.main-nav__logo > a > img'), 15)
    
  2. 使用关键字参数明确指定:
    如果担心顺序出错,可通过关键字参数传递,避免混淆:

    sel_ext.wait_until_visibility_of_element(locator=your_locator, timeout=15)
    
  3. 可选:添加参数校验
    在函数内增加类型校验,提前拦截错误输入:

    def wait_until_visibility_of_element(self, locator, timeout=None):
        timeout = timeout if timeout else self.default_timeout
        # 校验timeout类型
        if not isinstance(timeout, (int, float)):
            raise ValueError(f"超时时间必须是数字类型,当前传入: {type(timeout)}")
        WebDriverWait(self.driver, timeout).until(EC.visibility_of_element_located(locator))
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.25 10:07:34