Course Content
Selenium Python First Script
Selenium Python First Script
0/2
HTML Form elements
HTML Form elements
0/1
Handle HTML Frames
Handle HTML Frames
0/2
Handling Dropdown Lists
Handling Dropdown Lists
0/2
Selenium Action class
Selenium Action class
0/1
Selenium Python for Beginners [ 2024 ]
About Lesson

Selenium Python Alert Example

Sample page for testing the alerts is: 

https://testingdocs2016.blogspot.com/2014/06/alert-test.html

 

<br /># Handling Alerts Test Example
# www.TestingDocs.com

from selenium import webdriver 
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

driver = webdriver.Chrome() 
driver.get("https://testingdocs2016.blogspot.com/2014/06/alert-test.html")  

# Switch to the alert window 
#alert = driver.switch_to.alert(driver.find_element(By.NAME, "show_alert"))  

alert_button = driver.find_element(By.NAME, 'show_alert')
alert_button.click()

# Wait for the alert to display
wait = WebDriverWait(driver, 15)
alert = wait.until(EC.alert_is_present())

# Get the text from the alert
alert_text = alert.text
print(f'Alert text is: {alert_text}')

# Accept the alert
alert.accept()

# Close the browser
driver.quit()

Common error:

This is the common exception if the alert is not present or if the
script is not able to find the alert.

Error trace:
selenium.common.exceptions.NoAlertPresentException: Message: no such alert

Join the conversation