Selenium Implicit Wait VS Explicit Wait

本文介绍了Selenium WebDriver中隐式等待与显式等待的概念及其使用方法。隐式等待会在查找元素时持续轮询DOM直到超时。显式等待则为自定义条件,允许执行暂停直至满足特定条件或达到最大等待时间。

Implicit Wait: If elements are not immediately available, an implicit wait tells Web Driverto poll the DOM for a certain amount of time. The default setting is 0. Onceset, the implicit wait is set for the duration of the Web Driver object. 

Explicit Wait: It is the custom one. It will be used if we want the execution to wait forsome time until some condition achieved.

wait = WebDriverWait(self.driver, timeout=timeout, poll_frequency=pollFrequency,
                     ignored_exceptions=[NoSuchElementException,
                                         ElementNotVisibleException,
                                         ElementNotSelectableException])
element = wait.until(EC.element_to_be_clickable((byType, locator)))

timeout is how much time you want to wait before time is out. 

poll_frequency is the frequency of every poll.

ignored_exceptions is ignore those exceptions throwed. 

EC is Expected Condition. element_to_be_clickable is the expected condition.

byType, locator is where the element is. 



在自动化测试或系统性能调优中,等待时间的设置对于流程控制和性能优化至关重要。根据不同的应用场景,`waitTime` 的实现方式可以分为以下几类: ### 3.1 隐式等待(Implicit Wait) 隐式等待是一种全局设置,适用于所有元素查找操作。它会在指定的时间范围内不断轮询 DOM,直到找到目标元素为止;若超时仍未找到,则抛出异常。这种方式避免了因页面加载延迟而导致的查找失败问题。 例如,在 Python 中使用 Selenium 设置隐式等待的方式如下: ```python self.driver.implicitly_wait(20) # 等待时间为20秒[^1] ``` 该设置在整个 WebDriver 实例生命周期内有效,并会对每次元素查找操作施加影响。虽然提高了脚本的健壮性,但也会增加整体执行时间,因为每个查找操作都会潜在地引入额外等待。 ### 3.2 显式等待(Explicit Wait) 显式等待是基于特定条件的等待机制,仅对特定操作生效。通常通过 `WebDriverWait` 结合预期条件(Expected Conditions)来实现。相比隐式等待,它更加灵活高效。 例如,等待某个元素在5秒内出现: ```python from selenium.webdriver.common.by import By from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC wait = WebDriverWait(self.driver, 5) element = wait.until(EC.presence_of_element_located((By.ID, 'query'))) # 等待id为'query'的元素出现[^4] ``` 此方法只针对特定元素进行等待,不会影响其他查找操作,适合用于异步加载内容或动态页面处理。 ### 3.3 强制等待(Hard Sleep) 强制等待通过 `time.sleep()` 方法实现,使程序暂停执行固定时间。虽然实现简单,但由于无法感知页面状态,容易造成不必要的等待时间浪费,降低测试效率。 ```python import time time.sleep(5) # 固定等待5秒[^1] ``` 因此,在大多数情况下应优先使用显式或隐式等待策略。 ### 3.4 数据库中的等待时间配置 在数据库层面,等待时间通常涉及事务锁、连接超时等参数。例如 MySQL 中的 `innodb_lock_wait_timeout` 控制事务等待行锁的时间,默认为50秒。若频繁出现“Lock wait timeout exceeded”错误,说明存在长事务或锁竞争问题,需通过优化索引、拆分事务等方式解决 [^3]。 此外,连接相关的等待如 `wait_timeout` 控制空闲连接的最大存活时间,过短会导致客户端频繁断开连接,引发通信错误。适当延长此类参数可提高稳定性。 ### 3.5 性能分析中的等待指标 从性能监控角度看,等待事件可通过如下指标进行量化分析 [^2]: - **Waits**:某类等待事件发生的总次数。 - **Total Wait Time**:该类等待的累计耗时(单位:秒)。 - **Avg Wait Time**:单次等待的平均耗时(微秒/毫秒)。 - **% DB Time**:该类等待占数据库总运行时间的比例。 - **Avg Active Sessions**:与此等待类别相关的并发会话数。 这些指标有助于识别系统瓶颈,指导资源调度与优化。 ---
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值