[Python] StaleElementReferenceException - Page randomly scrolls back up?

Discussão em 'Python' iniciado por Stack, Março 20, 2025.

  1. Stack

    Stack Membro Participativo

    url: https://www.wunderground.com/history/monthly/at/vienna/LOWW/date/2025-1

    It seems like I'm getting this exception because for some reason at a random point whilst iterating through the table the page scrolls back up so the table is not in the DOM anymore and so the table element can't be found.

    Any advice on how to avoid this? Thanks

    Code

    element = driver2.find_element(By.XPATH, '//*[@id="inner-content"]/div[2]/div[1]/div[5]/div[1]/div/lib-city-history-observation/div/div[2]/table')
    driver2.execute_script('arguments[0].scrollIntoView()', element)
    t = driver2.find_element(By.XPATH, '//*[@id="inner-content"]/div[2]/div[1]/div[5]/div[1]/div/lib-city-history-observation/div/div[2]/table/tbody/tr/td[1]/table')
    rows = t.find_elements(By.XPATH, './/tr')

    for row in rows:
    days = row.find_element(By.XPATH, './/td').text
    print(days)
    data.append({'days':days})


    Error

    StaleElementReferenceException Traceback (most recent call last)
    Cell In[14], line 32
    26 data = []
    31 for row in rows:
    ---> 32 days = row.find_element(By.XPATH, './/td').text
    33 driver2.execute_script('arguments[0].scrollIntoView()', element)
    34 print(days)

    Continue reading...

Compartilhe esta Página