Last active
August 20, 2025 18:22
-
-
Save cgoldberg/00f570e06ca26b17d2e3852d1b16cb1a to your computer and use it in GitHub Desktop.
Python - Selenium WebDriver function to wait for an element and click it
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python | |
# | |
# Selenium WebDriver function to wait for an element and click it | |
import time | |
from selenium import webdriver | |
from selenium.common.exceptions import ( | |
ElementClickInterceptedException, | |
StaleElementReferenceException, | |
TimeoutException, | |
) | |
from selenium.webdriver.common.by import By | |
from selenium.webdriver.support import expected_conditions as EC | |
from selenium.webdriver.support.wait import WebDriverWait | |
def wait_click(driver, locator, timeout=10): | |
"""Wait for an element and click it. | |
Args: | |
- driver - WebDriver instance | |
- locator - By locator for the desired element | |
- timeout - [Optional] How long to wait for the element (secs) | |
""" | |
expire = time.time() + timeout | |
while time.time() < expire: | |
wait = WebDriverWait(driver, timeout) | |
poll = wait._poll | |
try: | |
element = wait.until(EC.element_to_be_clickable((locator))) | |
element.click() | |
return element | |
except ElementClickInterceptedException: | |
time.sleep(poll) | |
except StaleElementReferenceException: | |
time.sleep(poll) | |
except TimeoutException: | |
break | |
raise TimeoutException( | |
f"Not able to click element <{locator}> within {timeout} secs." | |
) | |
# Example usage | |
if __name__ == "__main__": | |
driver = webdriver.Chrome() | |
driver.get("https://www.selenium.dev/selenium/web/inputs.html") | |
element = click(driver, (By.NAME, "checkbox_inpeut"), 5) | |
print(element.is_selected()) | |
driver.quit() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment