为什么通过硒切换到警报不稳定? [英] Why switching to alert through selenium is not stable?

查看:68
本文介绍了为什么通过硒切换到警报不稳定?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么通过硒切换为警报不稳定?

Why switching to alert through selenium is not stable?

例如.
1.运行代码,一切顺利.一切顺利. 但是,如果这段代码在几分钟内运行,则可能会出现错误. 例如,没有元素可以单击.依此类推.
2.在一个站点上,有一个警报窗口.

For example.
1. Run a code and all good. Everything worked out well. But if this code is run in a few minutes, then there may be errors. There is no element you can click on, for example. And so on.
2. On one site there is an alert window.

alert = driver.switch_to_alert()
alert.dismiss()

所以我将其关闭.但是他一直在工作.一切都好,然后是错误.

So I close it. But he works through time. All is well, then errors.

for al in range(3):
    try:
        alert = driver.switch_to_alert()
        alert.dismiss()
        time.sleep(randint(1, 3))
    except:
        pass

我写了所有内容,一切正常.
但是我认为这并不漂亮.
为什么一切都这么不稳定?
非常感谢.

I wrote and everything works out as it should.
But I think that this is not beautiful.
Why is everything so unstable?
Thank you very much.

推荐答案

根据您的代码块,您需要解决以下两个问题:

As per your code block there are a couple of issues which you need to address as follows :

  • Switching to an Alert : The method switch_to_alert() is Deprecated and you should be using switch_to.alert instead. The API Docs clearly mentions the following :

 def switch_to_alert(self):
     """ Deprecated use driver.switch_to.alert
     """
     warnings.warn("use driver.switch_to.alert instead", DeprecationWarning)
     return self._switch_to.alert

  • Wait for the Alert to be present : You should always induce WebDriverWait for the Alert to be present before invoking accept() or dismiss() as follows :

    WebDriverWait(driver, 5).until(EC.alert_is_present).dismiss()
    

  • 这篇关于为什么通过硒切换到警报不稳定?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

    查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆