Selenium Webdriver - Alerts



Selenium webdriver is capable of handling Alerts. The class selenium.webdriver.common.alert.Alert(driver) is used to work with Alerts. It has methods to accept, dismiss, enter and obtain the Alert text.

Methods

The methods under the Alert class are listed below −

  • accept() − For accepting an Alert.

  • dismiss() − For dismissing an Alert.

  • text() − For obtaining Alert text.

  • send_keys(keysToSend) − For entering text in Alert.

Code Implementation

The code implementation for alerts is as follows −

from selenium import webdriver
#import Alert class
from selenium.webdriver.common.alert import Alert
driver = webdriver.Chrome(executable_path='../drivers/chromedriver')
#implicit wait time
driver.implicitly_wait(0.8)
#url launch
driver.get("https://the-internet.herokuapp.com/javascript_alerts")
#identify element
l = driver.find_element_by_xpath("//*[text()='Click for JS Prompt']")
l.click()
# instance of Alert class
a = Alert(driver)
# get alert text
print(a.text)
#input text in Alert
a.send_keys('Tutorialspoint')
#dismiss alert
a.dismiss()
l.click()
#accept alert
a.accept()
#driver quit
driver.quit()

Output

JS Prompt

The output shows the message - Process with exit code 0 meaning that the above Python code executed successfully. Also, the Alert text - I am a JS prompt gets printed in the console.

Advertisements