0
0
Selenium Pythontesting~5 mins

New window and tab creation in Selenium Python

Choose your learning style9 modes available
Introduction

Sometimes, websites open new windows or tabs. Testing these helps ensure your app works well with multiple pages.

When a link opens a new tab to show extra information.
When clicking a button launches a new browser window.
When testing pop-ups that appear in separate windows.
When verifying that switching between tabs keeps data intact.
When automating workflows that require multiple pages open.
Syntax
Selenium Python
driver.switch_to.new_window('tab')
driver.switch_to.new_window('window')

Use 'tab' to open a new browser tab.

Use 'window' to open a new browser window.

Examples
Open a new tab and load a website there.
Selenium Python
driver.switch_to.new_window('tab')
driver.get('https://example.com')
Open a new window and load a website there.
Selenium Python
driver.switch_to.new_window('window')
driver.get('https://example.com')
Sample Program

This script opens three pages: one in the original tab, one in a new tab, and one in a new window. It prints each page's title to confirm the switch worked.

Selenium Python
from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.common.by import By
import time

# Setup Chrome driver
service = Service()
driver = webdriver.Chrome(service=service)

try:
    # Open first page
    driver.get('https://example.com')
    print('First page title:', driver.title)

    # Open new tab
    driver.switch_to.new_window('tab')
    driver.get('https://www.python.org')
    print('Second page title:', driver.title)

    # Open new window
    driver.switch_to.new_window('window')
    driver.get('https://www.selenium.dev')
    print('Third page title:', driver.title)

    # Close all
    driver.quit()
except Exception as e:
    print('Error:', e)
    driver.quit()
OutputSuccess
Important Notes

Always switch to the new window or tab before interacting with it.

Remember to close windows or tabs you open to avoid clutter.

Use driver.window_handles to see all open windows and tabs.

Summary

Use driver.switch_to.new_window('tab') to open a new tab.

Use driver.switch_to.new_window('window') to open a new window.

Switching focus is needed to control the new tab or window.