Search code examples
pythonseleniumselenium-webdrivernosuchelementexception

How to check if an html element is attached to the page document


So I am using a loop in python with selenium to constantly check on the attributes of a list of html elements, however once in a while one of the elements gets deattached from the document and another one is added in its place. when I try to check the attribute of the deattached element, it throws the error "stale element reference". I have searched about it and have found "NoSuchElementException" from selenium that supposedly would help me avoid this problem, however I do not know who to implement it correctly. Any other solutions/help with "NoSuchElementException" would be awesome :D


Solution

  • basically you want to wrap the code that throws an error in a try except statement. smthn like this

     try:
         #this will always run
         #some code - eg. check element attributes
     except NoSuchElementException:
         # this will be executed if NoSuchElementException error is raised by code in try block
         # here you can do whatever you need