【问题标题】:Python Selenium: stale element reference: element is not attached to the page documentPython Selenium:过时的元素参考:元素未附加到页面文档
【发布时间】:2019-04-27 04:53:34
【问题描述】:

我的程序抛出错误消息“过时的元素引用:元素未附加到页面文档”。翻看之前的帖子(如Python Selenium stale element fix),发现调用click函数后并没有更新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()

【问题讨论】:

    标签: python python-3.x selenium


    【解决方案1】:

    这是使用 Selenium 时最令人沮丧的错误之一。 我建议这样尝试:

    for tab in ['answers', 'questions']:
      js = "window.tab = [...document.querySelectorAll('div.tabs > a')].filter(a => a.innerText === '" + tab + "')[0]"
      driver.execute_script(js)
      driver.execute_script("if(window.tab) window.tab.click()")
      time.sleep(3)
      print(driver.current_url)
    

    通过在浏览器上下文中进行选择,您可以避免过时的引用。

    【讨论】:

      【解决方案2】:

      当您通过单击链接或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)
      

      【讨论】:

      • 我喜欢这个答案,但它仍然需要inner_tab.get_attribute("href") 不炸弹,这有点乐观。
      • @pguardiario 谢谢,我还是个新手,我需要了解更多关于硒的知识:D
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-12-13
      • 2016-10-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-12-15
      • 1970-01-01
      相关资源
      最近更新 更多