Verify page title and URL after navigation
Preconditions (2)
✅ Expected Result: The page title matches 'Example Domain' and the URL matches 'https://example.com/' exactly.
from selenium import webdriver from selenium.webdriver.chrome.service import Service from selenium.webdriver.chrome.options import Options import unittest class TestPageTitleAndURL(unittest.TestCase): def setUp(self): options = Options() options.add_argument('--headless') # Run in headless mode for testing self.driver = webdriver.Chrome(service=Service(), options=options) def test_title_and_url(self): self.driver.get('https://example.com') title = self.driver.title current_url = self.driver.current_url self.assertEqual(title, 'Example Domain', f"Expected title 'Example Domain' but got '{title}'") self.assertEqual(current_url, 'https://example.com/', f"Expected URL 'https://example.com/' but got '{current_url}'") def tearDown(self): self.driver.quit() if __name__ == '__main__': unittest.main()
The setUp method initializes the Chrome WebDriver in headless mode to run tests without opening a visible browser window.
The test_title_and_url method navigates to 'https://example.com', retrieves the page title and current URL, then asserts both match the expected values exactly.
The tearDown method ensures the browser closes after the test, freeing resources.
This structure uses Python's unittest framework for clear setup, test, and cleanup phases, making the test reliable and easy to maintain.
Now add data-driven testing with 3 different URLs and their expected titles
driver.titledriver.title property returns the title of the current page as a string.driver.page_source returns the HTML source, driver.current_url returns the URL, and driver.get_title() is not a valid method in Selenium Python.driver.current_url is a property that returns the current page URL as a string.driver.get_current_url(), driver.url(), and driver.getUrl use invalid method names or syntax. Only url = driver.current_url is correct without parentheses.print(driver.title) print(driver.current_url)
driver.title returns the page title string, here "Welcome Page".driver.current_url returns the current URL string, here "https://example.com/home".print(driver.get_title()) print(driver.get_current_url())
get_title() or get_current_url() in Selenium Python WebDriver.driver.title and driver.current_url without parentheses as they are properties, not methods.driver.title to get the page title and driver.current_url to get the URL. Use == to check exact title and 'in' to check substring in URL.Pass the test and this pattern moves unknown