selenium.common.exceptions.UnexpectedAlertPresentException: Alert Text报错

背景: 执行driver.execute_script("return document.readyState;")方法时因为当前浏览器有alert弹窗,导致报错:selenium.common.exceptions.UnexpectedAlertPresentException: Alert Text

详细报错信息如下:
		raise exception_class(message, screen, stacktrace, alert_text)
selenium.common.exceptions.UnexpectedAlertPresentException: Alert Text: {Alert text :
Message: unexpected alert open: {Alert text : }
  (Session info: chrome=90.0.4430.212)

原因分析:`

众所周知JavaScript是单线程,而alert属于同步方法,JS引擎主线程的第一优先级就是执行同步代码,一旦它占住了主线程其他的代码就得靠边,强行执行肯定抛异常~


解决思路:
  • 先加个if判断当前是否存在alert,根据alert弹窗的类型(是自动消失型还是必须要点击“确定”才能关闭)做处理
以下是Python3代码:
        while True:
        	Non_blocking = None
            try:
                if self.driver.switch_to.alert:
                	log.info("Alert info =={}".format(self.driver.switch_to.alert.text))
                	Non_blocking = False
                	#如果alert弹窗是需要点击确定或关闭,那么做相应操作
                    self.driver.switch_to.alert.accept()
                    self.driver.switch_to.alert.dismiss()
                    
            except Exception as e:
            	log.warning(e)
            	Non_blocking = True
            if Non_blocking:
                if self.execute_script("return document.readyState;") == "complete":
                    break
                else:
                    log.info('Sleep 0.3 seconds')
                    time.sleep(0.3)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

木法星人

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值