[파이썬] Selenium 조건부 대기 (Explicit Wait)

When automating web testing using Selenium, it is crucial to ensure that your script waits for specific conditions to be met before proceeding to the next step. Rather than using static waits, which can cause your script to fail if the network is slow or the element takes longer to load, explicit wait allows you to wait for a certain condition to occur before proceeding.

Explicit wait helps to synchronize your script with the web page by waiting for a specific element to be visible, clickable, or in a certain state. This allows for more reliable and stable test automation.

How to use Explicit Wait in Selenium

Explicit waits in Selenium are implemented using the WebDriverWait class and the expected_conditions module. Here’s an example of how to use explicit wait in 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

# Create a new instance of Firefox driver
driver = webdriver.Firefox()

# Open a website
driver.get("https://example.com")

# Specify the condition to wait for (e.g., an element to be visible)
condition = EC.visibility_of_element_located((By.ID, "element_id"))

# Create an explicit wait with a maximum timeout of 10 seconds
wait = WebDriverWait(driver, 10)

# Wait until the condition is met
element = wait.until(condition)

# Perform further actions on the element
element.click()

# Close the browser
driver.quit()

In this example, we first import the necessary modules from Selenium. Next, we create a new instance of the web driver (in this case, Firefox) and navigate to a website. We then specify the condition we want to wait for (in this case, an element with a specific ID to be visible).

We create an instance of WebDriverWait with a maximum timeout of 10 seconds and use the until method to wait until the condition is met. Once the condition is met, we can perform further actions on the element, such as clicking it.

Finally, we close the browser using the quit method.

Common Expected Conditions

Selenium provides a range of expected conditions that can be used with explicit wait. Here are some commonly used ones:

You can find more expected conditions in the Selenium documentation.

Conclusion

Using explicit wait in Selenium allows you to make your test scripts more robust and reliable by synchronizing them with the web page. By waiting for specific conditions to be met, you can avoid timing-related issues and create more stable test automation.

Remember to use explicit wait when necessary, rather than relying on static waits that may not be optimal for different scenarios. Happy testing!