wait_for_non_empty_text() under Selenium 4

54 Views Asked by At

I have successfully used wait_for_non_empty_text() from this discussion: How to wait for presence of an element with non empty content? in my Selenium v3 project, but after upgrade to Selenium 4, there is no longer _find_element() function in expected_conditions module, so wait_for_non_empty_text() no longer works.

Looks like Python\Python311\Lib\site-packages\selenium\webdriver\support\expected_conditions.py was completely re-written for Selenium 4.

Is there a way to change this custom expected condition to still be able to call this function using "wait.until()" under Selenium 4?

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

    def __call__(self, driver):
        try:
            element_text = EC._find_element(driver, self.locator).text.strip()
            return element_text != ""
        except StaleElementReferenceException:
            return False

I tried for hours but cannot figure out how to make it work without _find_element().

Thanks!

1

There are 1 best solutions below

6
Jortega On

I would suggest updating your code to something like the following. First add these 3 imports to help locate the element you are looking for.

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

Next I will give an example of how to use those in the code you provided. Update: Assuming the function is called like this wait_for_non_empty_text((By.ID, "test")).

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

    def __call__(self, driver):
        try:
            # Your old code
            # element_text = EC._find_element(driver, self.locator).text.strip()
            # New Example:
            element_text =  WebDriverWait(driver, 10).until(EC.presence_of_element_located(self.locator)).text.strip()
            return element_text != ""
        except StaleElementReferenceException:
            return False