Saturday, November 16, 2024
Google search engine
HomeLanguagesOpening and Closing Tabs Using Selenium

Opening and Closing Tabs Using Selenium

Selenium is a tool which is used to automate browser instructions. It is utilitarian for all programs, deals with all significant OS and its contents are written in different languages i.e Python, Java, C# etc. 

In this article, we are using Python as the language and Chrome as the WebDriver.

Installation

Python selenium module can be installed using the below command:

pip install selenium

Chrome Driver can be downloaded from Chrome Driver (version == 87.0.4).

Opening a Tab Using Selenium

In order to open a tab, a web driver is needed. In this, we are using Chrome Webdriver. After providing the driver path, use .get(URL) method to open a tab.

Python3




# Import module
from selenium import webdriver
  
# Create object
driver = webdriver.Chrome()
  
# Assign URL
  
# Fetching the Url
driver.get(url)


Output:

Opening a New tab using Selenium

In order to open a new tab, a javascript function to open a tab in a new window can be used. In order to use the functionality of javascript .executescript() method of selenium can be used. After executing the script we can switch to the window using .switch_to_window() method.

Python3




# import module
from selenium import webdriver
  
# Create object
driver = webdriver.Chrome()
  
# Assign URL
  
# New Url
  
# Opening first url
driver.get(url)
  
# Open a new window
driver.execute_script("window.open('');")
  
# Switch to the new window and open new URL
driver.switch_to.window(driver.window_handles[1])
driver.get(new_url)


Output:

Closing the Tab using Selenium:

In order to close the tab, .close() method is used.

Python3




# Import module
from selenium import webdriver
  
# Create object
driver = webdriver.Chrome()
  
# Fetching the Url
  
# Opening first url
driver.get(url)
  
# Closing the tab
driver.close()


Output:

Closing a Tab and switching to a new Tab using Selenium:

In the case of multiple tabs, after closing the tab using .close() method we can switch to the tab which is not closed using .switch_to_window() method.

Python3




# Import module
from selenium import webdriver
  
# Create object
driver = webdriver.Chrome()
  
# Fetching the Url
  
# New Url
  
# Opening first url
driver.get(url)
  
# Open a new window
driver.execute_script("window.open('');")
  
# Switch to the new window and open new URL
driver.switch_to.window(driver.window_handles[1])
driver.get(new_url)
  
# Closing new_url tab
driver.close()
  
# Switching to old tab
driver.switch_to.window(driver.window_handles[0])


Output:

Dominic Rubhabha-Wardslaus
Dominic Rubhabha-Wardslaushttp://wardslaus.com
infosec,malicious & dos attacks generator, boot rom exploit philanthropist , wild hacker , game developer,
RELATED ARTICLES

Most Popular

Recent Comments