在 Python 中如何使用 Selenium 了解页面是否有警报?

How to understand that a page has an alert or not with use of Selenium in Python?

Python中使用Selenium在网页中与alerts交互的解决方案有很多。但是,我想要一个解决方案来发现该页面有 alert 或没有。在我的案例中,使用 Try & except 是非常糟糕的解决方案。所以,不要提出那个。我只想要一个简单的 if & else 解决方案。 这是我的解决方案:

if driver.switch_to_alert()
  alert = driver.switch_to_alert()
  alert.accept()
else:
  print('hello')

NoAlertPresentException: no such alert
  (Session info: chrome=73.0.3683.103)
  (Driver info: chromedriver=2.46.628402 (536cd7adbad73a3783fdc2cab92ab2ba7ec361e1),platform=Windows NT 10.0.16299 x86_64)

当您自动化回归测试用例时,您总是知道网页上哪里有警报。根据当前的实现,要切换到 Alert,您需要使用:

  • switch_to.alert()如下:

    selenium.webdriver.common.alert 
    driver.switch_to.alert().accept()
    
  • 根据最佳实践,您应该始终为 alert_is_present() 引入 WebDriverWait,同时切换到 Alert如下:

    from selenium.webdriver.support.ui import WebDriverWait
    from selenium.webdriver.common.by import By
    from selenium.webdriver.support import expected_conditions as EC
    # other lines of code
    WebDriverWait(driver, 5).until(EC.alert_is_present).accept()
    
  • 要验证页面是否具有 Alert,理想的方法是结束 Alert 处理代码块try-catch{} 块中,如下所示:

    from selenium.webdriver.support.ui import WebDriverWait
    from selenium.webdriver.common.by import By
    from selenium.webdriver.support import expected_conditions as EC
    from selenium.common.exceptions import TimeoutException
    
    try:
        WebDriverWait(driver, 5).until(EC.alert_is_present).accept()
        print("Alert accepted")
    except TimeoutException:
        print("No Alert was present")
    

参考

您可以在以下位置找到一些相关讨论:


结尾

在某些情况下,您可能需要与无法通过 css/xpath 在 google-chrome-devtools 中检查的元素进行交互,您将在中找到详细讨论

你可以这样做:

driver.executeScript("window.alert = () => window.alertHappened = true")
// some code here that may cause alert
alert_happened = driver.executeScript("return !!window.alertHappened")