0
0
Selenium Pythontesting~10 mins

Handling multiple pages in Selenium Python - Test Execution Trace

Choose your learning style9 modes available
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.

Test Code - Selenium
Selenium Python
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()
Execution Trace - 8 Steps
StepActionSystem StateAssertionResult
1Test starts and Chrome browser opensBrowser window is open and ready-PASS
2Navigates to 'https://example.com'Example.com homepage is loaded-PASS
3Stores current window handle as original_windowOne browser tab open with example.com-PASS
4Finds link with text 'More information...' and clicks itNew browser tab/window opens with new page-PASS
5Waits until number of windows is 2Two browser tabs/windows openNumber of windows equals 2PASS
6Switches to the new window that is not original_windowDriver controls new browser tab/window-PASS
7Checks that new page title is 'IANA — IANA-managed Reserved Domains'New page is fully loadedPage title equals expected stringPASS
8Test ends and browser closesNo browser windows open-PASS
Failure Scenario
Failing Condition: The link with text 'More information...' is not found or new window does not open
Execution Trace Quiz - 3 Questions
Test your understanding
What does the test do after clicking the link that opens a new page?
ARefreshes the current page
BCloses the original window immediately
CWaits for the new window to open and switches to it
DClicks the link again
Key Result
Always store the original window handle before opening a new page, then wait for the new window and switch to it before interacting or asserting on the new page.