0

(using Selenium Webdriver on Python)

I have an explicit wait that I use to wait until an element is visible. Then extract the text from the element:

    def wait_and_get_text(self, locator, timeout=None):
    timeout = timeout if timeout else self.default_timeout
    try:
        element = WebDriverWait(self.driver, timeout).until(EC.visibility_of_element_located(locator))
    except TimeoutException:
        raise Exception(f"Presence of element {locator} was not detected after a timeout of {timeout}.")

    element_text = element.text
    return element_text

This function works except when I try to extract from a td element e.g. (By.CSS_SELECTOR, '.username-td') Then it returns the text as 'None'

If I remove the explicit wait and just type self.driver.find_element("css selector", ".username-td").text then the text does get extracted. But then I have no explicit wait. Does anyone know why this is the case with 'td' elements?

Roy idiot
  • 21
  • 4

1 Answers1

0

When you try to extract from the text from the <td> element i.e.

By.CSS_SELECTOR, '.username-td'

Then it returns the text as None as in the wait_and_get_text() method you are passing timeout=None by default which is later assigned to timeout and used within the WebDriverWait as follows:

def wait_and_get_text(self, locator, timeout=None):
timeout = timeout if timeout else self.default_timeout
try:
    element = WebDriverWait(self.driver, timeout).until(EC.visibility_of_element_located(locator))
    

So, though syntactically you have a WebDriverWait but functionally with a timeout=None the wait time is NULL.

Hence Selenium tries to extract the text immediately and subsequently prints None


Solution

Supply a valid value as a timeout, as an example to set 5 seconds:

def wait_and_get_text(self, locator, timeout=5):
undetected Selenium
  • 183,867
  • 41
  • 278
  • 352