Hamed Baziyad
Hamed Baziyad

Reputation: 2019

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

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)

Upvotes: 1

Views: 558

Answers (2)

pguardiario
pguardiario

Reputation: 54984

You can do:

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

Upvotes: 1

undetected Selenium
undetected Selenium

Reputation: 193108

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

Upvotes: 1

Related Questions