乐闻世界logo
搜索文章和话题

What is an explicit wait in Selenium?

1个答案

1

Explicit wait is a crucial concept in the Selenium automation testing framework, used to set conditions that must be satisfied before proceeding with code execution. It is primarily used to handle network latency and rendering delays, ensuring elements are interactive.

When using explicit wait, we not only specify the duration to wait but also define a waiting condition. This means Selenium periodically checks if the condition is met. If the condition is satisfied within the specified time, Selenium continues with the subsequent script; if the time expires and the condition is not met, Selenium throws a timeout exception.

Explicit wait is typically implemented using WebDriver's WebDriverWait and expected_conditions classes. Here is a simple example:

python
from selenium import webdriver from selenium.webdriver.common.by import By from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC # Launch Chrome browser driver = webdriver.Chrome() # Access a page driver.get("http://some-url.com") try: # Set explicit wait, maximum 10 seconds element = WebDriverWait(driver, 10).until( EC.presence_of_element_located((By.ID, "some-id")) ) # If element is found, perform actions element.click() finally: # Finally close the browser driver.quit()

In this example, WebDriverWait works with expected_conditions to wait until the element with ID 'some-id' appears in the DOM and is visible. If the element appears and is visible within 10 seconds, it proceeds to execute element.click(); if the element is still not visible after 10 seconds, it throws a TimeoutException.

Explicit wait is a very useful approach that increases the stability and reliability of tests, especially when dealing with dynamically loaded content.

2024年8月14日 00:04 回复

你的答案