Open In App

Close specific Web page using Selenium in Python

Prerequisites: Selenium Basics, Selenium close() and quit() 

Selenium is a powerful tool for controlling web browsers through programs and performing browser automation. It is functional for all browsers, works on all major OS and its scripts are written in various languages i.e Python, Java, C#, etc, we will be working with Python.



The close() method is a web driver command which closes the browser window. During the automation process, if there are multiple browser windows opened, then the close() command will close the current browser window that is having attention at that time. 

Requirements:



You need to install chromedriver and set path. Click here to download.for more information follows this link.

Step-by-step Approach:




# import modules
from selenium import webdriver
from selenium.webdriver.support.ui import Select
import time




# assign web page url




# find XPath
driver.find_element_by_xpath('//*[@id="Tabbed"]/a/button').click()




# return all handles value of open browser window
handles = driver.window_handles
  
for i in handles:
    driver.switch_to.window(i)
  
    # close specified web page
    if driver.title == "Frames & windows":
        time.sleep(2)
        driver.close()

The close() method closes current window page. Some pages are used for a long time some pages used for  short time. If we want to close a specific web page, we need to use some condition.

Implementation:




# import modules
from selenium import webdriver
from selenium.webdriver.support.ui import Select
import time
  
# use chrome driver
driver = webdriver.Chrome()
  
# assign web page url
  
# find XPath
driver.find_element_by_xpath('//*[@id="Tabbed"]/a/button').click()
  
# return all handles value of open browser window
handles = driver.window_handles
  
for i in handles:
    driver.switch_to.window(i)
  
    # close specified web page
    if driver.title == "Frames & windows":
        time.sleep(2)
        driver.close()

Output:


Article Tags :