PYTHON & SELENIUM. How to navgate to mutiple href BUT error: StaleElementReferenceException: stale element reference: stale element not found

46 views Asked by At

I post here my little code in order to find/scrap data by multiple pages.

from selenium import webdriver
from selenium.webdriver.common.by import By
import time

driver= webdriver.Chrome()
driver.get('https://www.xxxxxx.xx/')
ALL_HREF = driver.find_elements(By.XPATH,"//*[contains(@href, 'h2h-stats')]")
for LINK in ALL_HREF:
    time.sleep(2)
    LINK.click()
    driver.refresh()
    driver.back()
    time.sleep(2)
driver.quit()

the problem is that when I go back to the mainpage, in order to navigate to the 2th "href", I'm in error: StaleElementReferenceException: stale element reference: stale element not found (Session info: chrome=121.0.6167.187)

1

There are 1 answers

0
Wonka On

I solve doing this

...

ALL_HREF = driver.find_elements(By.XPATH,"//*[contains(@href, 'h2h-stats')]")
for i_a in range(len(ALL_HREF)):

    ALL_HREF[i_a].click()
    #sleep

    #Do what you need to do
    ...

    #Go back

    ALL_HREF = driver.find_elements(By.XPATH,"//*[contains(@href, 'h2h-stats')]")