Bartłomiej 'furas' Burek
furas.pl
# prywatne notatki - Python, Linux, Machine Learning, etc.

Selenium: How to close alert created by JavaScript

JavaScript can create three standard popup alerts: alert(), confirm() or prompt().

  • all of them have button OK
  • confirm() and prompt() have button CANCEL
  • prompt() has text field

To press button OK

driver.switch_to.alert.accept()  # press OK

To press button CANCEL (only in confirm() and prompt())

driver.switch_to.alert.dismiss()  # press CANCEL

To put some text in prompt() before accepting it

prompt = driver.switch_to.alert
prompt.send_keys('foo bar')
prompt.accept()

Probably in other languages there is function get_alert() to check if alert is acctually displayed but Python doesn't have it. But you can put code in try/except to catch error when there is no alert.

try:
    driver.switch_to.alert.accept()  # press OK
    #driver.switch_to.alert.dismiss()  # press CANCEL
except Exception as ex:
    print('Exception:', ex)

Minimal working example.

Because I don't know page which displays alert so I use execute_script() to display alert.

I also use console.log() to see in DevTool what result it sends to JavaScript.

First part checks code when alert is displayed. Second part check code when there is no alert.

from selenium import webdriver
import time

#driver = webdriver.Firefox()
driver = webdriver.Chrome()

driver.get('http://google.com')

# --- test when there is alert ---

driver.execute_script("console.log('alert: ' + alert('Hello World!'))")
#driver.execute_script("console.log('alert: ' + confirm('Hello World!'))")
#driver.execute_script("console.log('alert: ' + prompt('Hello World!'))")
time.sleep(2)

try:
    driver.switch_to.alert.accept()  # press OK
    #driver.switch_to.alert.dismiss()  # press CANCEL
except Exception as ex:
    print('Exception:', ex)

# --- test when there is no alert ---

try:
    driver.switch_to.alert.accept()  # press OK
    #driver.switch_to.alert.dismiss()  # press CANCEL
except Exception as ex:
    print('Exception:', ex)

# ---

driver.save_screenshot('image.png')
driver.close()

If you want to first try to press CANCEL and when it doesn't work then press OK

try:
    driver.switch_to.alert.dismiss()  # press CANCEL
except Exception as ex:
    print('Exception:', ex)
    try:
        driver.switch_to.alert.accept()   # press OK
    except Exception as ex:
        print('Exception:', ex)
Książki: python-dla-kazdego-podstawy-programowania python-wprowadzenie python-leksykon-kieszonkowy python-receptury python-programuj-szybko-i-wydajnie python-projekty-do-wykorzystania black-hat-python-jezyk-python-dla-hackerow-i-pentesterow efektywny-python-59-sposobow-na-lepszy-kod tdd-w-praktyce-niezawodny-kod-w-jezyku-python aplikacje-internetowe-z-django-najlepsze-receptury