6

I have following code in my web page.

<div id="" class="user_acc_setails">
<ul id="accDtlUL">
<li>First Name: <span id="f_name">Anuja</span></li>

By the time page loading, the value for Sapn is not set. It will take very small time to set the value. I want to wait and get that value in my Python file.

I'm currently using following code,

element = context.browser.find_element_by_id('f_name')
assert element.text == 'Anuja'

But it gives me an AssetionError. How can I solve this?

Thanks

AnujAroshA
  • 4,623
  • 8
  • 56
  • 99

5 Answers5

6

Correct way it this case would be to use Explicit waits (see Python code there). So you need something like

from selenium.webdriver.support import expected_conditions as EC
wait = WebDriverWait(driver, 10)
element = wait.until(EC.text_to_be_present_in_element((By.Id,'f_name'), 'Anuja'))
Petr Mensik
  • 26,874
  • 17
  • 90
  • 115
4

here's a function that does that;

def wait_on_element_text(self, by_type, element, text):
        WebDriverWait(self.driver, 10).until(
            ec.text_to_be_present_in_element(
                (by_type, element), text)
        )

Where by_type replace with e.g. By.XPATH, By.CSS_SELECTOR . Where element replace with the element path - the elements xpath, unique selector, id etc. Where text replace with the element's text e.g. the string associated with the element.

Ste
  • 41
  • 1
1
url = "http://..."
driver = webdriver.Firefox()
driver.get(url)

wait = WebDriverWait(driver, 10)
try:
    present = wait.until(EC.text_to_be_present_in_element((By.CLASS_NAME, "myclassname"), "valueyouwanttomatch"))
    elem = driver.find_element_by_class_name("myclassname")
    print elem.text
finally:
driver.quit()

I realized that the return object of wait.until is not an elem but a boolean variable, so I have to recall the locate element again.

B.Mr.W.
  • 18,910
  • 35
  • 114
  • 178
  • How do you get `text_to_be_present_in_element` if the class name is repeated, but the text is different? As a workaround, I've been using `presence_of_element_located((By.CLASS_NAME, "repeatclassname"))`, but I would prefer referencing the location of the repeated class, with a specific value. – datalifenyc Feb 04 '20 at 19:15
0

I found a solution. May be this is not the correct way. What I have done is used Python sleep before finding element and Assert it's value.

import time
...

time.sleep(3)
element = context.browser.find_element_by_id('f_name')
assert element.text == 'Anuja'

Then it is working perfectly.

AnujAroshA
  • 4,623
  • 8
  • 56
  • 99
  • 2
    No it isn't, explicit waits are the answer to your problem: http://docs.seleniumhq.org/docs/04_webdriver_advanced.jsp – Arran Sep 04 '13 at 08:07
0

You can use browser.implicitly_wait(2) command to wait browser implicitly.

from selenium import webdriver
browser = webdriver.Firefox()
browser.implicitly_wait(2)