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

Selenium中如何正确调用等待元素可点击的函数?

解决_wait_and_click函数调用的TypeError问题

嘿,这个问题一看就是参数格式不匹配导致的,咱们来快速搞定它:

错误原因

你现在调用函数时传的是元组格式的定位器:(By.ID, 'next-button'),但函数内部的代码是按照字典格式来处理的——它试图用locator["by"]和locator["value"]去取键对应的值,可元组只能用数字索引(比如locator[0]、locator[1]),自然就触发了tuple indices must be integers, not str的错误。

两种解决方案

方案1:按照函数原设计,传递字典格式的定位器

直接修改调用代码,把元组换成包含by和value键的字典:

_wait_and_click(self, {"by": By.ID, "value": 'next-button'}, 60)

这样函数就能正常解析locator["by"]和locator["value"]了。

方案2:修改函数,让它同时支持元组和字典(更灵活)

如果想保留你原来的元组调用方式,可以给函数加个格式判断逻辑,兼容两种定位器格式:

def _wait_and_click(self, locator, timeout):
    try:
        wait = WebDriverWait(self.driver, timeout)
        # 新增:处理不同格式的locator
        if isinstance(locator, tuple):
            target_locator = locator
        elif isinstance(locator, dict):
            target_locator = (locator["by"], locator["value"])
        else:
            raise ValueError("Locator must be a tuple (like (By.ID, 'id')) or dictionary with 'by' and 'value' keys")
        
        wait.until(expected_conditions.element_to_be_clickable(target_locator)).click()
    except TimeoutException:
        return False
    return True

修改后,你原来的元组调用方式_wait_and_click(self, (By.ID, 'next-button'), 60)就能正常运行了。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.28 09:38:30