stale element reference: element is not attached to the page document 错误

参考博客
https://www.jianshu.com/p/32e9442cf9c8

https://www.cnblogs.com/fengpingfan/p/4583325.html

官方文档中的解释:
https://selenium-python-zh.readthedocs.io/en/latest/api.html#module-selenium.common.exceptions

  • 这个错误的意思是:如果你之前定位了某个元素,在之后页面刷新后,这个元素需要重新获取否则可能报错
  • 这个错误并不是每次都会发生,所以可以捕获,然后在捕获代码重新调用**“指定的方法”**

下面代码在 12 行可能出错,所以在 except 中继续调用该方法

def next_page(page_num):

    try:
        next_page_btn = wait.until(
            EC.presence_of_element_located((By.CSS_SELECTOR,'#J_bottomPage > span.p-num > a.pn-next > em'))
        )

        time.sleep(2)           # 暂定两秒 
        # 点击下一页
        next_page_btn = driver.find_element(By.CSS_SELECTOR,'#J_bottomPage > span.p-num > a.pn-next > em')

        next_page_btn.click()				# 可能出错的位置 
    except StaleElementReferenceException:
        next_page(page_num)

猜你喜欢

转载自blog.csdn.net/hi_bigguy/article/details/83380673
今日推荐