New window and tab creation in Selenium Python - Build an Automation Script
from selenium import webdriver from selenium.webdriver.common.by import By from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC # Initialize WebDriver with webdriver.Chrome() as driver: wait = WebDriverWait(driver, 10) # Step 1: Open main page driver.get('https://example.com') original_window = driver.current_window_handle # Step 2: Click element that opens new window # Assuming button with id 'open-window' open_window_button = wait.until(EC.element_to_be_clickable((By.ID, 'open-window'))) open_window_button.click() # Step 3: Wait for new window and switch wait.until(EC.number_of_windows_to_be(2)) new_window = [w for w in driver.window_handles if w != original_window][0] driver.switch_to.window(new_window) # Step 4: Verify new window title wait.until(EC.title_is('New Window Title')) assert driver.title == 'New Window Title', f"Expected title 'New Window Title' but got '{driver.title}'" # Step 5: Close new window and switch back driver.close() driver.switch_to.window(original_window) # Step 6: Open new tab driver.execute_script("window.open('about:blank', '_blank');") wait.until(EC.number_of_windows_to_be(2)) new_tab = [w for w in driver.window_handles if w != original_window][0] driver.switch_to.window(new_tab) # Step 7: Navigate new tab to URL driver.get('https://example.com/newtab') # Step 8: Verify new tab URL wait.until(EC.url_to_be('https://example.com/newtab')) assert driver.current_url == 'https://example.com/newtab', f"Expected URL 'https://example.com/newtab' but got '{driver.current_url}'" # Step 9: Close new tab and switch back driver.close() driver.switch_to.window(original_window) # Final assertion to confirm back to original window assert driver.current_window_handle == original_window, "Did not switch back to original window"
This script uses Selenium WebDriver with Python to automate the test case.
First, it opens the main page and stores the original window handle.
Then it clicks a button that opens a new window, waits until the new window appears, and switches to it.
It verifies the new window's title matches the expected value.
After verification, it closes the new window and switches back to the original window.
Next, it opens a new tab using JavaScript, switches to it, navigates to the specified URL, and verifies the URL.
Finally, it closes the new tab and switches back to the original window, asserting the switch was successful.
Explicit waits ensure the script waits for elements and conditions properly, avoiding flaky tests.
Using window handles allows precise control over browser windows and tabs.
Now add data-driven testing to open new windows and tabs with 3 different URLs and verify their titles or URLs accordingly.