【问题标题】:Why switching to alert through selenium is not stable?为什么通过硒切换到警报不稳定?
【发布时间】:2018-07-28 02:31:58
【问题描述】:

为什么通过 selenium 切换到 alert 不稳定?

例如。
1.运行一个代码,一切都好。一切都很顺利。 但是如果这段代码在几分钟内运行,那么可能会出现错误。 例如,没有可以单击的元素。等等。
2. 在一个站点上有一个警告窗口。

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

所以我关闭它。但他会随着时间的推移而工作。一切正常,然后出错。

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

我写了,一切正常。
但我认为这并不美丽。
为什么一切都如此不稳定?
非常感谢。

【问题讨论】:

  • 是否有多个警报?多个标签?如果您只是解除警报一次,究竟什么会停止工作?也许您需要显式切换回主窗口/选项卡。
  • 请提供一个完整的代码示例,该示例有时有效,有时无效,即mcve。你的第二部分有点混乱。 一切正常,但并不漂亮暗示了一个不同的问题。
  • Selenium 只能用于测试而不是抓取。

标签: python google-chrome selenium firefox selenium-webdriver


【解决方案1】:

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

  • Switching to an Alertswitch_to_alert() 方法已弃用,您应该改用 switch_to.alert。 API Docs 清楚地提到了以下内容:

     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 :在调用 accept()dismiss() 之前,您应该始终诱导 WebDriverWait 以使 Alert 存在,如下所示:

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

【讨论】:

    【解决方案2】:

    这将单击警报上的确定按钮:

    driver.switch_to.alert.accept() 
    

    这将单击警报上的 CANCEL 按钮:

    driver.switch_to.alert.dismiss()     
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-06-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-09-26
      • 2018-09-15
      • 2012-01-08
      • 2013-10-20
      相关资源
      最近更新 更多