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.
Practice
Solution
Step 1: Understand Selenium's new window method
Selenium providesdriver.switch_to.new_window()to open new tabs or windows by specifying the type as 'tab' or 'window'.Step 2: Identify the correct argument for a new tab
To open a new tab, the argument must be the string 'tab'. So the correct command isdriver.switch_to.new_window('tab').Final Answer:
driver.switch_to.new_window('tab') -> Option AQuick Check:
Open new tab = driver.switch_to.new_window('tab') [OK]
- Using non-existent methods like driver.open_new_tab()
- Passing 'window' instead of 'tab' to open a tab
- Trying driver.new_tab() which is invalid
Solution
Step 1: Recall the method to open new windows
Selenium's correct method isdriver.switch_to.new_window()with argument 'window' to open a new window.Step 2: Check syntax correctness
Onlydriver.switch_to.new_window('window')uses the correct method and argument.driver.new_window('window')anddriver.open_window('window')use invalid method names, anddriver.switch_to.new_window('tab')opens a tab, not a window.Final Answer:
driver.switch_to.new_window('window') -> Option BQuick Check:
Open new window = driver.switch_to.new_window('window') [OK]
- Confusing 'tab' and 'window' arguments
- Using wrong method names like driver.new_window()
- Missing the switch_to part in the command
driver.get('https://example.com')
original_handle = driver.current_window_handle
driver.switch_to.new_window('tab')
driver.get('https://selenium.dev')
print(len(driver.window_handles))Solution
Step 1: Analyze window handles before and after new tab
Initially, the driver opens one window (example.com). Afterdriver.switch_to.new_window('tab'), a new tab opens, so total windows/tabs become 2.Step 2: Count window handles
Thedriver.window_handleslist contains all open windows/tabs. After opening the new tab, its length is 2.Final Answer:
2 -> Option AQuick Check:
New tab adds one handle, total handles = 2 [OK]
- Assuming window_handles length stays 1 after new tab
- Confusing current_window_handle with window_handles list
- Expecting an error due to missing switch focus
driver.get('https://example.com')
driver.new_window('tab')
driver.get('https://selenium.dev')Solution
Step 1: Check method usage for opening new tab
The correct method to open a new tab isdriver.switch_to.new_window('tab'). The code missesswitch_to.Step 2: Understand why missing switch_to causes error
Callingdriver.new_window('tab')directly is invalid and will raise an AttributeError.Final Answer:
Missing driver.switch_to before new_window() -> Option CQuick Check:
Use driver.switch_to.new_window() to open tabs/windows [OK]
- Calling new_window() directly on driver
- Thinking driver.get() limits opening new tabs
- Believing driver.get() can only be called once
Solution
Step 1: Save original window handle before opening new tab
Storedriver.current_window_handlein a variable to switch back later.Step 2: Open new tab and load URL
Usedriver.switch_to.new_window('tab')to open a new tab, then load the URL withdriver.get().Step 3: Switch back to original tab
Usedriver.switch_to.window(original)to return focus to the original tab.Final Answer:
Code snippet D correctly opens a new tab, loads URL, and switches back -> Option DQuick Check:
Save handle, open tab, load URL, switch back [OK]
- Not saving original window handle before opening new tab
- Using 'window' instead of 'tab' when a tab is needed
- Switching back to original tab before loading the URL in the new tab
Ready to prove it?
Pass the test and this pattern moves unknown
