Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Wait for element to be clickable using python and Selenium

There are ways to wait for an object e.g. a button to be clickable in selenium python. I use time.sleep() and/or WebDriverWait...until, it works fine.

However, when there are hundreds of objects, is there a way to set a default time lag globally, instead of implementing it on each object?

The click() action should have a conditional wait time?

like image 676
Heinz Avatar asked Sep 04 '25 17:09

Heinz


1 Answers

I come up with this:

from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By

def myClick(by, desc):
    wait = WebDriverWait(driver, 10)
    by = by.upper()
    if by == 'XPATH':
        wait.until(EC.element_to_be_clickable((By.XPATH, desc))).click()
    if by == 'ID':
        wait.until(EC.element_to_be_clickable((By.ID, desc))).click()
    if by == 'LINK_TEXT':
        wait.until(EC.element_to_be_clickable((By.LINK_TEXT, desc))).click()

with this function, the code:

driver.find_element_by_link_text('Show Latest Permit').click()

will be

myClick('link_text', 'Show Latest Permit')

instead.

I have run a couple weeks with hundreds of elements to click, I have not seen the errors any longer.

like image 126
Heinz Avatar answered Sep 07 '25 08:09

Heinz