Selenium WebDriver controls one window or tab at a time. When a new window or tab opens, Selenium does not automatically switch to it. You must explicitly tell Selenium to switch its context to the new window to interact with elements inside it.
from selenium import webdriver from selenium.webdriver.common.by import By import time browser = webdriver.Chrome() browser.get('https://example.com') original_window = browser.current_window_handle browser.execute_script("window.open('https://example.org', '_blank');") time.sleep(1) print(len(browser.window_handles)) browser.quit()
The code opens the initial page, then opens a new tab with window.open. This results in two windows/tabs open, so len(browser.window_handles) returns 2.
new_window = [handle for handle in driver.window_handles if handle != original_window][0] driver.switch_to.window(new_window) # Which assertion below is correct?
The driver.current_window_handle property holds the handle of the window Selenium is currently controlling. After switching, it should equal the new window's handle.
driver.get('https://example.com') driver.execute_script("window.open('https://example.org', '_blank');") button = driver.find_element(By.ID, 'submit') button.click()
After opening a new window, Selenium still controls the original window. Without switching to the new window, Selenium tries to find the button in the original window, causing failure.
Because new windows may take time to open, storing the original handles and waiting until a new handle appears before switching ensures the test does not fail due to timing issues.