Selenium is an open-source web-based automation tool. We'll learn how to handle alert and pop-up windows in Selenium using Python. Let's take a look at each one separately.
We'll handle alerts using the following methods.
driver.switch_to.alert
: This method will switch focus to the alert box and return an instance of the alert.alert.accept()
: This method will accept the alert.alert.dismiss()
: This method will dismiss the alert box.Let's take a look at an example code of this.
from selenium import webdriver import time #specify where your chrome driver present in your pc PATH=r"C:\Users\educative\Documents\chromedriver\chromedriver.exe" #get instance of web driver driver = webdriver.Chrome(PATH) #provide website url here driver.get("https://omayo.blogspot.com/") #sleep for 2 seconds time.sleep(2) #get button and click on it to get alert driver.find_element("id","alert1").click() #switch to alert box alert = driver.switch_to.alert #sleep for a second time.sleep(1) #accept the alert alert.accept()
driver.get()
method to open the given URL.accept()
method to accept the alert box.We'll handle the pop-up window using the following methods.
driver.window_handles[1]
: This method gets the instance of the pop-up window.driver.switch_to.window(handle)
: This method switches to the given pop-up window.driver.close()
: This method closes the current window.from selenium import webdriver import time #specify where your chrome driver present in your pc PATH=r"C:\Users\educative\Documents\chromedriver\chromedriver.exe" #get instance of web driver driver = webdriver.Chrome(PATH) #provide website url here driver.get("https://omayo.blogspot.com/") #sleep for 2 seconds time.sleep(2) #click on the link to get popup popup_link = driver.find_element("xpath", '//*[@id="HTML37"]/div[1]/p/a').click() #get instance of first pop up window whandle = driver.window_handles[1] #switch to pop up window driver.switch_to.window(whandle) #get text of a element in pop window print(driver.find_element("id","para1").text) #sleep for 1 second time.sleep(1) #closes current window driver.close()
driver.window_handles
method to get the child windows.switch_to.window()
method. After switching focus to the popup window, we can interact with it like a regular window.driver.close()
method to close the current window, a popup window in our case.RELATED TAGS
CONTRIBUTOR
View all Courses