2

Is there an existing way in Selenium WebDriver to wait until an element gains or loses a class? For example, the HTML for my select looks like this:

<select id="select-1" class="selectBox ui-state-error" row-index="0" tabindex="-1" aria-hidden="true">
...
</select>

The class in question is ui-state-error. This basically displays a red highlight on my drop down. Basically, I want to set up an explicit wait until my select element gains the class ui-state-error or loses the class ui-state-error.

I'm not sure if this is even possible.

Python version: 3.4.3. Python bindings for Selenium: 2.46.0

SpartaSixZero
  • 2,183
  • 5
  • 27
  • 46

1 Answers1

3

There is no built-in way to achieve it. You would need to write a custom Expected Condition:

from selenium.webdriver.support import expected_conditions as EC

class wait_for_class(object):
    def __init__(self, locator, class_name):
        self.locator = locator
        self.class_name = class_name

    def __call__(self, driver):
        try:
            element_class = EC._find_element(driver, self.locator).get_attribute('class')
            return element_class and self.class_name in element_class
        except StaleElementReferenceException:
            return False

Usage:

wait = WebDriverWait(driver, 10)
wait.until(wait_for_class((By.ID, 'select-1'), "ui-state-error"))

Expected conditions are, basically callables, which means you can just write a function instead, but I like to follow the way they are implemented as classes internally in python-selenium.

Community
  • 1
  • 1
alecxe
  • 462,703
  • 120
  • 1,088
  • 1,195