Search code examples
pythonseleniumwebdriver

Which expected_conditions to use?


I have this list on a website using Python's Selenium.

enter image description here

Clicking an item opens a sublist where you can click multiple buttons. I click these buttons with JavaScript so that the sublist never opens. This method is faster.

...
driver.execute_script(button)

My question is which expected_conditions should I use to wait for the buttons to appear in the DOM so that I can select it with JavaScript?

expected_conditions.element_to_be_clickable (what I use all the time) isn't the right answer.


Solution

  • As you are not expanding the items and sublist being invisible you are invoking click() on multiple buttons, WebDriverWait for visibility_of_element_located() and element_to_be_clickable() will always fail.


    Solution

    In such cases, your best bet would be to induce WebDriverWait for the presence_of_element_located() as follows:

    element = WebDriverWait(driver, 20).until(expected_conditions.presence_of_element_located((By.XPATH, "element_xpath']")))
    driver.execute_script(""arguments[0].click();", element)
    

    In a single line:

    driver.execute_script(""arguments[0].click();", WebDriverWait(driver, 20).until(expected_conditions.presence_of_element_located((By.XPATH, "element_xpath']"))))
    

    Another JavaScript based alternative would be:

    driver.execute_script("document.getElementsByClassName('theClassName')[0].click()")