Handling multiple pages 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 def test_multiple_page_navigation(): driver = webdriver.Chrome() wait = WebDriverWait(driver, 10) try: # Step 1: Open home page driver.get('https://example.com/home') # Step 2: Click 'About Us' link about_link = wait.until(EC.element_to_be_clickable((By.LINK_TEXT, 'About Us'))) about_link.click() # Step 3: Verify URL is about page wait.until(EC.url_to_be('https://example.com/about')) assert driver.current_url == 'https://example.com/about', f"Expected URL to be 'https://example.com/about' but got {driver.current_url}" # Step 4: Verify heading on About page about_heading = wait.until(EC.visibility_of_element_located((By.TAG_NAME, 'h1'))) assert about_heading.text == 'About Our Company', f"Expected heading 'About Our Company' but got '{about_heading.text}'" # Step 5: Click 'Contact' link contact_link = wait.until(EC.element_to_be_clickable((By.LINK_TEXT, 'Contact'))) contact_link.click() # Step 6: Verify URL is contact page wait.until(EC.url_to_be('https://example.com/contact')) assert driver.current_url == 'https://example.com/contact', f"Expected URL to be 'https://example.com/contact' but got {driver.current_url}" # Step 7: Verify heading on Contact page contact_heading = wait.until(EC.visibility_of_element_located((By.TAG_NAME, 'h1'))) assert contact_heading.text == 'Contact Information', f"Expected heading 'Contact Information' but got '{contact_heading.text}'" finally: driver.quit()
This test script uses Selenium WebDriver with Python to automate the manual test case.
We start by opening the browser and navigating to the home page URL.
We use explicit waits to wait until the 'About Us' link is clickable, then click it.
We wait until the URL changes to the About page URL and assert it matches exactly.
We then wait for the heading element (assumed to be an <h1>) to be visible and check its text.
Next, we click the 'Contact' link similarly, wait for the URL to update, and verify the heading on the Contact page.
Finally, we close the browser in a finally block to ensure cleanup even if assertions fail.
This approach uses best practices like explicit waits and meaningful locators to make the test reliable and readable.
Now add data-driven testing with 3 different navigation paths and verify their URLs and headings.