0
0
Selenium Pythontesting~15 mins

Opening URLs (get) in Selenium Python - Build an Automation Script

Choose your learning style9 modes available
Open a web page using Selenium WebDriver
Preconditions (3)
Step 1: Launch the browser using Selenium WebDriver
Step 2: Navigate to the URL 'https://example.com' using the get() method
Step 3: Verify that the browser has loaded the page by checking the current URL
✅ Expected Result: The browser opens and loads the page at 'https://example.com'. The current URL matches 'https://example.com'.
Automation Requirements - selenium
Assertions Needed:
Verify the current URL is exactly 'https://example.com'
Best Practices:
Use explicit waits if needed (not required here since get() waits for page load)
Use By locators only when interacting with elements (not needed here)
Close the browser after test to free resources
Automated Solution
Selenium Python
from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.chrome.options import Options
import unittest

class TestOpenURL(unittest.TestCase):
    def setUp(self):
        options = Options()
        options.add_argument('--headless')  # Run browser in headless mode
        service = Service()  # Assumes chromedriver is in PATH
        self.driver = webdriver.Chrome(service=service, options=options)

    def test_open_example_com(self):
        url = 'https://example.com'
        self.driver.get(url)
        current_url = self.driver.current_url
        self.assertEqual(current_url, url, f"Expected URL to be {url} but got {current_url}")

    def tearDown(self):
        self.driver.quit()

if __name__ == '__main__':
    unittest.main()

This test uses Python's unittest framework and Selenium WebDriver.

setUp(): Initializes Chrome browser in headless mode to run without opening a window. It uses Service() assuming chromedriver is in PATH.

test_open_example_com(): Calls get() with the URL 'https://example.com'. Then it checks the current URL matches exactly using assertEqual. This confirms the page loaded correctly.

tearDown(): Closes the browser after the test to free resources.

This structure is clear and follows best practices: setup, test, teardown. The assertion is simple and direct.

Common Mistakes - 3 Pitfalls
Not closing the browser after the test
{'mistake': 'Using time.sleep() instead of relying on get() to wait for page load', 'why_bad': 'Unnecessary waits slow tests and are unreliable for page load timing.', 'correct_approach': "Selenium's get() waits for the page to load, so explicit waits or sleeps are not needed here."}
Checking page content before verifying URL
Bonus Challenge

Now add data-driven testing to open three different URLs and verify each loads correctly.

Show Hint