【问题标题】:StaleElementReferenceException when iterating through dynamical iterable迭代动态可迭代对象时出现 StaleElementReferenceException
【发布时间】:2020-07-09 11:06:16
【问题描述】:

我想通过循环遍历所有 webElements 来向下滚动网站,我正在这样做:

driver.get('https://justjoin.it/')
driver.maximize_window()

while True:
    for web_element in driver.find_elements_by_class_name('css-1x9zltl'):
        driver.execute_script("arguments[0].scrollIntoView();", web_element)

不幸的是,几秒钟后滚动条停止并且控制台向我抛出了这个异常:

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

寻找解决方案我搜索了很多网页,现在我知道为什么会出现这种类型的错误。我试图通过使用 try/except 来解决这个问题,它可以工作,但当然它并不能解决问题的本质。我想知道有没有更好的方法来解决我的问题?

【问题讨论】:

    标签: python-3.x selenium selenium-chromedriver staleelementreferenceexception


    【解决方案1】:

    也许您在 justjoin.it 页面加载并“稳定”之前调用 find_elements_by_class_name()。然后,当您循环浏览您收集的元素时,页面会继续加载并使这些收集的元素对象无效。我会尝试在调用 driver.get() 和调用 find_elements_by_class_name() 之间等待更长时间。

    【讨论】:

    • 我把 time.sleep(10) 放在了 while True 和 for web_element in... 之间,控制台仍然给我同样的错误;/
    【解决方案2】:

    当元素在页面中但 selenium 驱动程序实例无法与该元素交互时发生过时元素异常。

    以下操作可以解决陈旧元素异常

    1.在selenium中使用“navigate().refresh()”方法刷新页面

    2.如果该元素可见或已单击退出循环,则使用循环尝试单击或检查该元素的可见性

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-06-03
      • 1970-01-01
      • 1970-01-01
      • 2023-03-09
      • 2014-03-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多