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

Selenium 4中如何修改wait_for_non_empty_text自定义等待条件?

Selenium 4 适配自定义等待条件 wait_for_non_empty_text 的修改方案

Selenium 4 完全重写了expected_conditions模块,原代码依赖的私有方法EC._find_element已被移除,只需替换元素查找逻辑即可修复自定义等待条件。

修改后的完整代码

from selenium.common.exceptions import StaleElementReferenceException
from selenium.webdriver.support.ui import WebDriverWait

class wait_for_non_empty_text(object):
    def __init__(self, locator):
        self.locator = locator

    def __call__(self, driver):
        try:
            # 替换原EC._find_element,直接用driver的find_element方法定位
            element = driver.find_element(*self.locator)
            element_text = element.text.strip()
            return element_text != ""
        except StaleElementReferenceException:
            return False

关键修改点

  • 移除对EC._find_element的调用,改用driver.find_element(*self.locator)直接定位元素(locator需保持元组格式,比如(By.ID, "element_id"))
  • 确保导入StaleElementReferenceException异常类,避免未定义错误
  • 保留原有核心逻辑:获取元素文本并去空格后判断是否非空,遇到元素过期异常时返回False,让等待继续执行

使用示例

# 假设已初始化好driver实例
wait = WebDriverWait(driver, 10)
# 等待目标元素文本非空
wait.until(wait_for_non_empty_text((By.CSS_SELECTOR, ".target-element")))

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.14 19:09:51