Renan Gomes
Renan Gomes

Reputation: 829

How to wait for presence of an element with non empty content?

How can I wait for a presence of an element which the content (text) is not empty? I tried select by xpath using //*[@id="test" and text() != ""], but the return of WebDriverWait#until does not retrieve the element.

My code:

selector = '//*[@id="test" and text() != ""]'
element = WebDriverWait(driver, timeout).until(
  expected_conditions.presence_of_element_located((By.XPATH, selector))
)

I would like to get the text content of the element. I tried:

print element.text # prints 0

If i print only element, the output is <selenium.webdriver.remote.webelement.WebElement(session="xxx", element="xxx")>. What is wrong?

The div I'm tryin to get has this structure:

<div>
   Test:
   <div id="test"><b>this text here</b></div>
</div>

Upvotes: 4

Views: 7879

Answers (2)

Sergey
Sergey

Reputation: 341

You can wait for an element by xpath with non empty text like this:

xpath = "//*[@id='test']"

WebDriverWait(driver, 30).until(lambda driver: driver.find_element_by_xpath(xpath).text.strip() != '')

source

Upvotes: 3

alecxe
alecxe

Reputation: 473813

The text() xpath function would not help in this case since it would not consider the texts of the child elements. You actually need to call the .text in your Expected Condition. You can create a custom one:

from selenium.webdriver.support import expected_conditions as EC

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

Usage:

wait = WebDriverWait(driver, timeout)
element = wait.until(
    wait_for_non_empty_text((By.ID, "test"))
)
print(element.text)

Upvotes: 2

Related Questions