how to get text with Selenium in the python from <span class> if appears for few seconds?

Viewed 118

I have a question related to getting a text from span class with Selenium in the Python script. I've already checked many variants to get text, but still no luck. The main reason - mentioned element appears on the page for several seconds and disappears and I need to get "Latest" text from that element.

Here is element, which appears for few seconds:

 </style><div class="PNs8Z result_1613936507015"><span class="genericPhrase" data-role="final_result">Latest</span></div></div></div></div>

I've already tried several approaches, which I found in the Selenium documentation and in the Internet:

wait.until(presence_of_element_located((By.CSS_SELECTOR, "span.final_result")))
WebDriverWait(driver, 30).until(EC.find_element_by_xpath("//span[contains(@class,'final_result')]"))
WebDriverWait(driver, 30).until(EC.visibility_of_element_located((By.CSS_SELECTOR, "div.final_result")))

But, still no luck. I found solutions when the element permanently on the page and doesn't disappear, but that approach hasn't worked yet for me.

Maybe somebody has already faced such an issue and has a ready solution for my case?

Thanks in advance. Ihor

3 Answers

To search xpath of such dynamic elements use DOM break points:

enter image description here

And select break on subtree modification. Now all changes will break and pause the webpage rendering

enter image description here

Click resume execution or press f8 till your span gets displayed

To get the value Latest which is inside span tag use following xpath

Try with .text

print(WebDriverWait(driver, 10).until(EC.visibility_of_element_located((By.XPATH,"//span[@class='genericPhrase' and @data-role='final_result']"))).text)

Or Try with .get_attribute("textContent")

print(WebDriverWait(driver, 10).until(EC.visibility_of_element_located((By.XPATH,"//span[@class='genericPhrase' and @data-role='final_result']"))).get_attribute("textContent"))

 

Maybe you are incorrectly identifying your locator. Try

driver.find_element_by_css_selector(".genericPhrase").text

To wait for visibility use:

from selenium.webdriver.support.wait import WebDriverWait

wait = WebDriverWait(driver, timeout=20)           
wait.until(EC.visibility_of_element_located((SelectBy.CSS_SELECTOR, ".genericPhrase")))
Related