Jasmine
Jasmine

Reputation: 25

Message: stale element reference: element is not attached to the page document while clicking on multiple links on the webpage using Selenium Python

I'm trying to click on every possible course links on this page, but it gave me this error:

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

This is my code:

driver = webdriver.Chrome()
driver.get('https://catalog.maryville.edu/preview_program.php?catoid=18&poid=3085&_ga=2.22513656.232086776.1594848572-196623372.1594848572')
driver.implicitly_wait(10)
links = driver.find_elements_by_xpath('//*[@id="table_block_n2_and_content_wrapper"]/table/tbody/tr[2]/td[1]/table/tbody/tr/td/table/tbody/tr[2]/td/div/div/ul/li/span/a')

for link in links:
    driver.execute_script("arguments[0].click();", link)
    time.sleep(3)
driver.quit()

Any idea how to fix this?

Upvotes: 1

Views: 122

Answers (1)

undetected Selenium
undetected Selenium

Reputation: 193108

To click on all the course links on the page https://catalog.maryville.edu/preview_program.php?catoid=18&poid=3085&_ga=2.22513656.232086776.1594848572-196623372.1594848572 you can use either of the following Locator Strategies:

  • Using CSS_SELECTOR:

    driver.get("https://catalog.maryville.edu/preview_program.php?catoid=18&poid=3085&_ga=2.22513656.232086776.1594848572-196623372.1594848572")
    links = WebDriverWait(driver, 20).until(EC.visibility_of_all_elements_located((By.CSS_SELECTOR, "li.acalog-course>span>a")))
    for link in links:
        link.click()
        time.sleep(3)
    driver.quit()
    
  • Using XPATH:

    driver.get("https://catalog.maryville.edu/preview_program.php?catoid=18&poid=3085&_ga=2.22513656.232086776.1594848572-196623372.1594848572")
    links = WebDriverWait(driver, 20).until(EC.visibility_of_all_elements_located((By.XPATH, "//li[@class='acalog-course']/span/a")))
    for link in links:
        link.click()
        time.sleep(3)
    driver.quit()
    
  • Note : You have to add the following imports:

    from selenium.webdriver.support.ui import WebDriverWait
    from selenium.webdriver.common.by import By
    from selenium.webdriver.support import expected_conditions as EC
    

Reference

You can find a relevant detailed discussion on StaleElementReferenceException in:

Upvotes: 2

Related Questions