0

I have a html code which shows time.

<span class="inner-2pZN4z">09:37:24 (UTC-4)</span>

Now this will change every second to show the correct time (I think it uses javascript to update the time, because I don't see any class change.). Now I want to take the time in my python code. So, I executed:

driver.find_elements_by_xpath("//span[@class='inner-2pZN4z']").text

This throws an exception:

Message: stale element reference: element is not attached to the page document

Edit

I went through How to disable Javascript when using Selenium? but disabling JavaScript for me will not work as there are other codes which need JavaScript.

Question: How can we disable/enable JavaScript in while executing python code using selenium chromedriver?

stack
  • 27
  • 6
  • try with //span[contains(@class,'2pZN4z')], u can also try giving some wait before if page not loaded – murali selenium May 06 '21 at 13:45
  • @muraliselenium I think it uses javascript to update the time, because I don't see any class change. So contains will not solve I think – stack May 06 '21 at 13:49
  • It seem that page updated by JS each second, so element becomes stale. You might need to disable JS on WD start or try [this solution](https://stackoverflow.com/questions/1285917/how-to-disable-javascript-when-using-selenium/36782979#36782979) to disable it in runtime. P.S. Note that @class in code is not the same as in HTML – JaSON May 06 '21 at 14:55
  • The class was just copy-paste error while adding question to SO, JavaScript cannot be disabled, edit made to the question for the same @JaSON – stack May 06 '21 at 16:00
  • Just a guess, but perhaps the class name is dynamic also. Can you search by part of class name (that starts with 'inner-' ? Of if you know the path to the parent go there then get child. – Kevin Field May 06 '21 at 16:25
  • @KevinField I checked in console, class name doesn't changes. I tried `find_element_by_xpath("./following-sibling::")` then also same error. The issue is this error doesn't get triggered always at the same seconds, some time it will load til 30s some time 1s – stack May 06 '21 at 16:45
  • try with javascript executor.. – murali selenium May 07 '21 at 06:35
  • @muraliselenium sorry, I didn't get that... Could you please help me with an example? – stack May 07 '21 at 06:54
  • 1
    try `driver.execute_script('return document.querySelector(".inner-2pZN4z").textContent')` – JaSON May 07 '21 at 07:25
  • @JaSON how can I use querySelector for: `find_element_by_xpath("./following-sibling::*[3]/div[2]").text` ? – stack May 09 '21 at 07:01
  • Actually there is a way to use [XPath in JavaScript](https://stackoverflow.com/questions/10596417/is-there-a-way-to-get-element-by-xpath-using-javascript-in-selenium-webdriver) – JaSON May 11 '21 at 07:15

0 Answers0