Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to handle javascript alerts in selenium using python

So I there is this button I want to click and if it's the first time you've clicked it. A javascript alert popup will appear. I've been using firebug and just can't find where that javascript is located and I've tried

if EC.alert_is_present:
        driver.switch_to_alert().accept()
else:
    print("no alert")

the above code works if there is an alert box but will throw an error if there is none. even though there is an else statement I've even tried

   if EC.alert_is_present:
            driver.switch_to_alert().accept()
   elif not EC.alert_is_present:
               print("no alert")

it throws me this error

selenium.common.exceptions.NoAlertPresentException: Message: No alert is present

how do we get around this?

like image 663
Halcyon Abraham Ramirez Avatar asked May 09 '15 23:05

Halcyon Abraham Ramirez


2 Answers

Use try catch and if the Alert is not present catch NoAlertPresentException exception:

from selenium.common.exceptions import NoAlertPresentException

try:
    driver.switch_to_alert().accept()
except NoAlertPresentException as e: 
    print("no alert")
like image 87
Saifur Avatar answered Nov 15 '22 00:11

Saifur


This is how you do it:

from selenium.common.exceptions import NoAlertPresentException
try:
    context.driver.switch_to.alert.accept()
except NoAlertPresentException:
    pass

You can replace pass with a print statement if you wish. Note the use of switch_to.alert rather than switch_to_alert(). The latter has been deprecated for a while. In the version of Selenium I have here, I see this in its code:

warnings.warn("use driver.switch_to.alert instead", DeprecationWarning)
like image 26
Louis Avatar answered Nov 15 '22 01:11

Louis