About Lesson
Alert Class
The methods and properties of the Alert class are as follows:
- accept()
- dismiss()
- send_keys()
- text
The accept() method accepts the alert by clicking the OK button. This simulates the user clicking on the alert button displayed on the webpage. The dismiss() method cancels the alert by clicking the Cancel button. The send_keys() method types the specified text in the prompt alert box. The text fetches the alert text to a script variable.
Example
The example script illustrates the Alert class methods to handle the alert in Python. The driver.switch_to.alert() method switches the focus to the alert window.
# Handling Alerts Test Example
# www.TestingDocs.com
from selenium import webdriver
driver = webdriver.Chrome()
driver.get("https://www.example.com")
# Switch to the alert window
alert = driver.switch_to.alert
# Accept the alert
alert.accept()
# Dismiss the alert
alert.dismiss()
# Get the text from the alert
alert_text = alert.text
print(alert_text)
# Enter text in the prompt alert
alert.send_keys("Test text")
# Accept the prompt alert
alert.accept()