0leg
0leg

Reputation: 14144

Python, Selenium - handle multiple wait-conditions

I have a file called webdriver.py which implements methods from selenium.webdriver library. Had a wait-function that were handling most of the cases I need:

def wait_for(self, func, target=None, timeout=None, **kwargs):
    timeout = timeout or self.timeout
    try:
        return WebDriverWait(self, timeout).until(func)
    except TimeoutException:
        if not target:
            raise WebDriverException('Wait for: "%s" failed!' % inspect.getsource(func).strip())
        raise NoSuchElementException(target)

Where func is a selector.

The problem is that sometimes the DOM element would be invisible, causing exception and test failure. So I would like to extend wait_for to also wait for the element to become visible.

Something like

def wait_for(self, func, target=None, timeout=None, **kwargs):
    timeout = timeout or self.timeout
    try:
        return WebDriverWait(self, timeout).until(EC.element_to_be_clickable(func)).until(func)
    except TimeoutException:
        if not target:
            raise WebDriverException('Wait for: "%s" failed!' % inspect.getsource(func).strip())
        raise NoSuchElementException(target)

EC is a selenium.driver.expected_conditions

This would not work of course - either until().until() syntax is not supported.. or something else happens, like EC doesn't exist.

Any ideas?

Upvotes: 1

Views: 1275

Answers (1)

Mesut GUNES
Mesut GUNES

Reputation: 7401

You can use EC.presence_of_element_located for waiting an element in DOM to visible, no need for second .until.

def wait_for(self, func, target=None, timeout=self.timeout):
    try:
        WebDriverWait(self, timeout).until(EC.presence_of_element_located((By.CSS_SELECTOR, func)))
    except TimeoutException:
        if not target:
            raise WebDriverException('Wait for: "%s" failed!' % inspect.getsource(func).strip())
        raise NoSuchElementException(target)

Upvotes: 1

Related Questions