I am trying to get the innerText from all themessage.spoilers-container, but when I scroll up the webpage, the program crashes, and give me an error.
Code:
from selenium.common.exceptions import NoSuchElementException
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys
def find_message_container(driver):
    try:
        elements = driver.execute_script("return document.querySelectorAll('.message.spoilers-container')")
        unique_texts = set()
        for element in elements:
            text = element.get_attribute("innerText")
            if text not in unique_texts:
                unique_texts.add(text)
            with open("unique_texts.txt", "w") as file:
                for text in unique_texts:
                    file.write("\n" + text + "\n")
    except NoSuchElementException as e:
        print('Could not find the given element container. The following exception was raised:\n', e)
        pass
    
    return unique_texts
Error:
Traceback (most recent call last):
  File "c:\~\Desktop\Project\file.py", line 11, in find_message_container
    text = element.get_attribute("innerText")
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\~\AppData\Local\Programs\Python\Python311\Lib\site-packages\selenium\webdriver\remote\webelement.py", line 179, in get_attribute   
    attribute_value = self.parent.execute_script(
                      ^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\~\AppData\Local\Programs\Python\Python311\Lib\site-packages\selenium\webdriver\remote\webdriver.py", line 506, in execute_script   
    return self.execute(command, {"script": script, "args": converted_args})["value"]
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\~\AppData\Local\Programs\Python\Python311\Lib\site-packages\selenium\webdriver\remote\webdriver.py", line 444, in execute
    self.error_handler.check_response(response)
  File "C:\~\AppData\Local\Programs\Python\Python311\Lib\site-packages\selenium\webdriver\remote\errorhandler.py", line 249, in check_response
    raise exception_class(message, screen, stacktrace)
selenium.common.exceptions.StaleElementReferenceException: Message: stale element reference: element is not attached to the page document
  (Session info: chrome=109.0.5414.120)
What could cause this problem? The website I am testing this on is Web Telegram. Everytime new chats is loaded by scrolling up, a new container appears.
Any help would be helpful, I tried with some wait statements and wait.until, but it did not work.
 
     
    