Test Overview
This test opens a website, clicks a link that opens a new page, switches to the new page, and verifies the new page's title.
This test opens a website, clicks a link that opens a new page, switches to the new page, and verifies the new page's title.
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 import unittest class TestMultiplePages(unittest.TestCase): def setUp(self): self.driver = webdriver.Chrome() self.driver.implicitly_wait(5) def test_switch_to_new_page(self): driver = self.driver driver.get('https://example.com') original_window = driver.current_window_handle # Click link that opens new page link = driver.find_element(By.LINK_TEXT, 'More information...') link.click() # Wait for new window WebDriverWait(driver, 10).until(EC.number_of_windows_to_be(2)) # Switch to new window for window_handle in driver.window_handles: if window_handle != original_window: driver.switch_to.window(window_handle) break # Verify new page title self.assertEqual(driver.title, 'IANA — IANA-managed Reserved Domains') def tearDown(self): self.driver.quit() if __name__ == '__main__': unittest.main()
| Step | Action | System State | Assertion | Result |
|---|---|---|---|---|
| 1 | Test starts and Chrome browser opens | Browser window is open and ready | — | PASS |
| 2 | Navigates to 'https://example.com' | Example.com homepage is loaded | — | PASS |
| 3 | Stores current window handle as original_window | One browser tab open with example.com | — | PASS |
| 4 | Finds link with text 'More information...' and clicks it | New browser tab/window opens with new page | — | PASS |
| 5 | Waits until number of windows is 2 | Two browser tabs/windows open | Number of windows equals 2 | PASS |
| 6 | Switches to the new window that is not original_window | Driver controls new browser tab/window | — | PASS |
| 7 | Checks that new page title is 'IANA — IANA-managed Reserved Domains' | New page is fully loaded | Page title equals expected string | PASS |
| 8 | Test ends and browser closes | No browser windows open | — | PASS |
driver.window_handles return in Selenium?driver.window_handles returnsdriver.switch_to.window().driver.window_handles[1].main_window = driver.current_window_handle
all_windows = driver.window_handles
for window in all_windows:
driver.switch_to.window(window)
print(driver.title)
main_window = driver.current_window_handle # code to open new tab driver.switch_to.window(driver.window_handles[1]) # do something # switch back driver.switch_to.window(main_window())
driver.switch_to.window(main_window) without parentheses.driver.switch_to.window(original_handle) to return safely.Pass the test and this pattern moves unknown