Skip to content
Related Articles

Related Articles

Close specific Web page using Selenium in Python
  • Last Updated : 04 Jan, 2021

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 required modules

Python3




# import modules
from selenium import webdriver
from selenium.webdriver.support.ui import Select
import time
  • Taking any URL.

Python3




# assign web page url
  • We want the child window of this web page then click on any button.

  •  Copy XPath.

  • Use the find_element_by_xpath() method to find XPath.

Python3




# find XPath
driver.find_element_by_xpath('//*[@id="Tabbed"]/a/button').click()
  • Create a handles variable who store all handles value of the open browser window.
  • Then the specified condition of the closing web page.

Python3




# 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:

Python3




# 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:

 Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.  

To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course. And to begin with your Machine Learning Journey, join the Machine Learning – Basic Level Course

My Personal Notes arrow_drop_up
Recommended Articles
Page :