Python: How to Open New Tab and Switch between Tabs using Selenium

neotam Avatar

Python: How to Open New Tab and Switch between Tabs using Selenium
Posted on :

Tags :

Selenimum framework is mainly used for web testing. It provides the rich API to interact with browser and supports many different languages. This article will provide the simple code snippet to open the new tab with different URL and how to switch between tabs

import time
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.by import By

URL = 'https://getKT.com'
driver = webdriver.Firefox()
driver.get(URL)

time.sleep(3)

# Open new tab
new_url = 'https://example.com'
driver.execute_script(f' window.open("{new_url}", "_blank") ')

# Windows handles
tabs = driver.window_handles
print(f"Tabs: {tabs}")

time.sleep(3)
# To switch to first tab
driver.switch_to.window(tabs[0])

Explanation

First get the browser driver to interact with using “webdriver.Firefox()” to use Firefox browser. You may want to use Chrome or Ie instead of Firefox.

Following couple of lines open the browser windows with given URL

driver = webdriver.Firefox()
driver.get(URL)

To open the new tab with given URL, execute the JavaScript in the specified script as follows

new_url = 'https://example.com'
driver.execute_script(f' window.open("{new_url}", "_blank") ')

In this scenario, format string feature is used to fill in the variable new_url

To extract the all windows or tabs opened use “driver.window_handles”

# Windows handles
tabs = driver.window_handles
print(f"Tabs: {tabs}")

Where, driver.window_handles is the list of UUIDs representing the tabs. Pass the selected tab as an argument to “driver.switch_to.window” function as follws

driver.switch_to.window(tabs[0])

Leave a Reply

Your email address will not be published. Required fields are marked *