Using Selenium Python to Manage JavaScript Alerts

Posted by






Handling JavaScript Alerts using Selenium Python

Handling JavaScript Alerts using Selenium Python

When working with automated testing of web applications using Selenium and Python, it is common to encounter JavaScript alerts that need to be handled. JavaScript alerts are pop-up boxes that appear on a web page and require user interaction to dismiss them. In this article, we will discuss how to handle JavaScript alerts using Selenium Python.

Using WebDriver to handle alerts

Selenium provides a class called WebDriver, which can be used to interact with web elements on a web page. To handle JavaScript alerts, we can use the switch_to_alert() method of the WebDriver class.


from selenium import webdriver

driver = webdriver.Chrome()
driver.get('https://example.com')

# Click a button that triggers a JavaScript alert
button = driver.find_element_by_id('alert_button')
button.click()

# Switch to the alert and accept it
alert = driver.switch_to_alert()
alert.accept()

Handling different types of alerts

There are three types of JavaScript alerts: simple alerts, confirmation alerts, and prompt alerts. Simple alerts only require a single action to dismiss them, while confirmation and prompt alerts require the user to confirm or input some data, respectively. To handle these different types of alerts, we can use the accept() and dismiss() methods of the Alert class, as well as the send_keys() method for prompt alerts.


# Handling a confirmation alert
confirmation_alert = driver.switch_to_alert()
confirmation_alert.dismiss()

# Handling a prompt alert
prompt_alert = driver.switch_to_alert()
prompt_alert.send_keys('This is a test input')
prompt_alert.accept()

Conclusion

Handling JavaScript alerts is an important part of automated testing with Selenium Python. By using the switch_to_alert() method of the WebDriver class, we can easily interact with and dismiss JavaScript alerts on a web page. Additionally, by using the accept(), dismiss(), and send_keys() methods of the Alert class, we can handle different types of alerts with ease.


0 0 votes
Article Rating
1 Comment
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Chaithanya Moorpa
1 year ago

we are giving driver.quit() so you said earlier.. that method will close all the windows.. instead of that just give driver.close() then it will throw the Exception.