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 webdriverimport time#specify where your chrome driver present in your pcPATH=r"C:\Users\educative\Documents\chromedriver\chromedriver.exe"#get instance of web driverdriver = webdriver.Chrome(PATH)#provide website url heredriver.get("https://omayo.blogspot.com/")#sleep for 2 secondstime.sleep(2)#get button and click on it to get alertdriver.find_element("id","alert1").click()#switch to alert boxalert = driver.switch_to.alert#sleep for a secondtime.sleep(1)#accept the alertalert.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 webdriverimport time#specify where your chrome driver present in your pcPATH=r"C:\Users\educative\Documents\chromedriver\chromedriver.exe"#get instance of web driverdriver = webdriver.Chrome(PATH)#provide website url heredriver.get("https://omayo.blogspot.com/")#sleep for 2 secondstime.sleep(2)#click on the link to get popuppopup_link = driver.find_element("xpath", '//*[@id="HTML37"]/div[1]/p/a').click()#get instance of first pop up windowwhandle = driver.window_handles[1]#switch to pop up windowdriver.switch_to.window(whandle)#get text of a element in pop windowprint(driver.find_element("id","para1").text)#sleep for 1 secondtime.sleep(1)#closes current windowdriver.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.