Python + Selenium 报错 StaleElementReferenceException 解决方法

>>StaleElementReferenceException

  • 当引用的元素对象 ”过时“ 时抛出(页面刷新,窗口(标签页)切换,网址切换,当前页面下的”下一集“或”下一页“等操作都有可能引发对象过时错误)

  • ”过时“意味着之前你通过css ,xpath等方法定位的元素,暂未出现在当前DOM上,重新定位元素是解决方案之一

  • 原文解释:

Possible causes of StaleElementReferenceException include, but not
limited to:
You are no longer on the same page, or the page may have
refreshed since the element was located. The element may have been
removed and re-added to the screen, since it was located. Such as an
element being relocated. This can happen typically with a javascript
framework when values are updated and the node is rebuilt. Element may
have been inside an iframe or another context which was refreshed.

>>问题描述

  • 我在做一个模拟登陆+自动播放视频的脚本时,遇到了这个错误。具体原因就是一集进度结束后,点击播放下一集,页面没有跳转,没有出现新的窗口,网页链接没有改变,但页面元素重定向。导致find 方法 或者click 交互等操作报错。

>>解决方案

1. 引入等待步骤
  • 不管是显式、隐式、全局等待还是其他间隔性操作,达到元素对象刷新完毕后再交互的目的即可。
  • -举个栗子:
# 调出隐藏元素
donSee = WebDriverWait(self.api, 5, ).until(
    EC.presence_of_element_located((
    By.XPATH, "//div[@class='videoArea']" )))
onPear = self.api.find_element_by_xpath(
		"//span[@id='lessonOrder']")
self.action.move_to_element(onPear).pause(1). \
    move_to_element(donSee).pause(0.5)

# 倍速盒-->调整倍速
box = WebDriverWait(self.api, 6, ).until(
    EC.presence_of_element_located((
    By.XPATH, "//div[@class='speedBox']")))
rate = WebDriverWait(self.api, 6, ).until(
    EC.presence_of_element_located((
    By.XPATH, "//div[@class='speedBox']/div/div[@rate='1.5']")))
self.action.move_to_element(box).click().perform()
self.action.double_click(rate).perform()

2.页面元素重定向。
  • 如果使用Action模拟键鼠则需要释放当前元素,重新定位元素。
  • 举个例子:
def MediaPanel(self) :
    """
    一个高度封装的自动脚本的模块
    :return: 
    """
        try:
            self.MonitorProgress()  
            # 监听进度
            nex = self.api.find_element_by_xpath(
                "//div[@class='controlsBar']//div[@id='nextBtn']")
            # 本集播放结束,预备下一集工作
            self.action.move_to_element(onPear).pause(1). \
                move_to_element(donSee).pause(0.5).\
                click(nex).perform()
    		#模拟操作呼出隐藏面板,点击“下一集”按钮
        except StaleElementReferenceException:
        #当元素”过时“,执行以下操作
            self.action.reset_actions()
            # 关键语法-更新dom树-元素重定向
        finally:
            self.AudioPanel()
            #递归调用;重新定位元素
>>其他
>>Selenium 中其他类型错误
  • Selenium常见报错汇总(转译自官方API文档)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值