1

There are many solutions for interaction with alerts in web pages using Selenium in Python. But, I want a solution to find that the page has an alert or no. Use of Try & except is very bad solution in my case. So, don't present that. I want just a simple if & else solution. This is my solution:

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)
undetected Selenium
  • 183,867
  • 41
  • 278
  • 352
Hamed Baziyad
  • 1,954
  • 5
  • 27
  • 40
  • There is no way other than `try except`. Why is it so bad? – Guy Apr 14 '19 at 13:17
  • https://stackoverflow.com/questions/19003003/check-if-any-alert-exists-using-selenium-with-python And do you mean just window.alert? – QHarr Apr 14 '19 at 14:26

2 Answers2

1

When you automate the Regression Testcases you are always aware that where there is an alert on the webpage. As per the current implementation to switch to an Alert you need to use:

  • switch_to.alert() as follows:

    selenium.webdriver.common.alert 
    driver.switch_to.alert().accept()
    
  • As per best practices you should always induce WebDriverWait for the alert_is_present() while switching to an Alert as follows:

    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()
    
  • To validate that a page has an Alert or not the ideal approach would be to wrap up the Alert handling code block in a try-catch{} block as follows:

    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")
    

Reference

You can find a couple of relevant discussion in:


Outro

There may be some cases when you may need to interact with elements those cannot be inspected through css/xpath within google-chrome-devtools and you will find a detailed discussion in How to interact with elements those cannot be inspected through css/xpath within google-chrome-devtools

undetected Selenium
  • 183,867
  • 41
  • 278
  • 352
1

You can do:

driver.executeScript("window.alert = () => window.alertHappened = true")
// some code here that may cause alert
alert_happened = driver.executeScript("return !!window.alertHappened")
pguardiario
  • 53,827
  • 19
  • 119
  • 159