Home > Blockchain >  Selenium Hover over element gives me an Error AFTER is goes past the code?
Selenium Hover over element gives me an Error AFTER is goes past the code?

Time:06-28

I have the following code:

for button in buttons:
   
    ActionChains(driver).move_to_element(button).perform()
    time.sleep(2)
    button.click()
    time.sleep(2)
    try:
        wait_button.until(EC.presence_of_element_located((By.XPATH,'//div/h2')))
        time.sleep(2)
        name = driver.find_element_by_xpath('//div/h2').text
    except:
        wait_button.until(EC.presence_of_element_located((By.XPATH,'//span[@id="chat-header-title"]')))
        time.sleep(2)
        name = driver.find_element_by_xpath('//span[@id="chat-header-title"]').text
    
    
    def pull_ul() -> list:
        chat_frame = driver.find_element_by_xpath("//iframe[starts-with(@id, 'experience-container-')]")
        driver.switch_to.frame(chat_frame)
        wait_button.until(EC.presence_of_element_located((By.XPATH,'//ul[@aria-label="Chat content"]')))
        the_ul =driver.find_element(By.XPATH,'//ul[@aria-label="Chat content"]')
        new_lis =the_ul.find_elements(By.TAG_NAME,'li')
        return new_lis

    def pull_ul_again() -> list:
        the_ul =driver.find_element(By.XPATH,'//ul[@aria-label="Chat content"]')
        new_lis_2 =the_ul.find_elements(By.TAG_NAME,'li')
        return new_lis_2

    lis = pull_ul()
    print(f"Archiving Chat with {name} ...\n")
    print("this is len lis: ",len(lis), "for "   name)

And here is what the terminal shows: enter image description here

As you can see, the code actually does run past the line that threw up the error, how is this possible? Also, why would this be happening , I successfully ran the code multiple times and suddenly it starts throwing the follwing error?

CodePudding user response:

The loop that you're doing,

for button in buttons:
   
    ActionChains(driver).move_to_element(button).perform()
    ...

is causing your StaleElementReferenceException because inside that you have driver.switch_to.frame(chat_frame), but you never switch back to default content or to the parent frame, which means that your buttons won't exist in that level, and so Selenium throws StaleElementReferenceException as a result. That could also happen if you navigate away from the page (which might also be happening depending on the button clicks).

If you ever switch frames or leave pages, you have to re-find elements in order to interact with them.

  • Related