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

标签 python python-3.x selenium

我的程序抛出一条错误消息“过时的元素引用:元素未附加到页面文档”。当我查看以前的帖子(例如 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)

关于 python Selenium : stale element reference: element is not attached to the page document,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53465962/

相关文章:

python - 如何为python中的每个元素添加一个数字?

Python BigQuery allowLargeResults 与 pandas.io.gbq

python - 如何去掉输出中的括号和逗号?

python - 与从 stdin 读取的 C++ 代码等效的 Python 是什么?

c# - 直接点击元素与通过 Action 类点击元素的区别

python - 如何确保在命令之间接收到数据

Python pyqt4 从函数访问 QTextEdit

Python 高效地从 XML 中提取嵌套元素

python - 在 Python 中使用 Selenium Webdriver 下载图像

vba - Selenium-vba 按类名获取元素