Skip to main content
 首页 » 编程设计

python Selenium : stale element reference: element is not attached to the page document

2025年05月04日21linjiqin

我的程序抛出一条错误消息“过时的元素引用:元素未附加到页面文档”。当我查看以前的帖子(例如 Python Selenium stale element fix )时,我发现我在调用点击功能后并没有更新 url。我更新了网址。但是,它没有解决问题。谁能指出我在哪里犯了错误?这是我的代码:

chrome_options = webdriver.ChromeOptions() 
chrome_options.add_argument("--disable-infobars") 
driver = webdriver.Chrome(chrome_options=chrome_options,executable_path="path of driver here") 
 
driver.get("https://stackoverflow.com/users/37181/alex-gaynor?tab=topactivity") 
if driver.find_elements_by_xpath("//a[@class='grid--cell fc-white js-notice-close']"): 
    driver.find_element_by_xpath("//a[@class='grid--cell fc-white js-notice-close']").click() 
 
 
inner_tabs = driver.find_elements_by_xpath("//div[@class='tabs']//a") 
 
for inner_tab in inner_tabs: 
 
    if inner_tab.text == "answers": 
        inner_tab.click() 
        time.sleep(3) 
        driver.get(driver.current_url) 
        continue 
 
    if inner_tab.text == "questions": 
        inner_tab.click() 
        time.sleep(3) 
        driver.get(driver.current_url) 
        continue 
 
driver.quit() 

请您参考如下方法:

当您通过单击链接或 driver.get() 打开新 URL 时,它将创建新的文档元素,因此旧元素 (inner_tab) 将失效。要解决,首先收集所有 URL 然后循环打开。

urls_to_visit = [] 
 
for inner_tab in inner_tabs: 
    if inner_tab.text in ["questions", "answers"]: 
        urls_to_visit.append(inner_tab.get_attribute("href")) 
 
for url in urls_to_visit: 
    driver.get(url) 
    time.sleep(3)