Last modified: Nov 22, 2024 By Alexander Williams
Python Selenium: Get Current URL - Complete Guide
When working with web automation using Selenium, retrieving the current URL of a webpage is a fundamental task. This guide will show you how to effectively use the current_url
property in Python Selenium.
Understanding Current URL in Selenium
The current URL represents the actual address of the webpage that the WebDriver is currently accessing. This information is crucial for navigation verification and flow control in your automation scripts.
Basic Implementation
Here's a simple example of how to get the current URL using Selenium WebDriver:
from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.chrome.options import Options
# Setup Chrome WebDriver
chrome_options = Options()
service = Service('path/to/chromedriver')
driver = webdriver.Chrome(service=service, options=chrome_options)
# Navigate to a website
driver.get('https://www.example.com')
# Get current URL
current_url = driver.current_url
print(f"Current URL: {current_url}")
driver.quit()
Current URL: https://www.example.com
Practical Applications
The current_url
property is particularly useful when dealing with redirects or when you need to verify that your automation script has reached the correct page. Like in handling href attributes.
URL Verification Example
def verify_navigation(driver, expected_url):
# Get current URL and compare with expected URL
actual_url = driver.current_url
try:
assert expected_url in actual_url
print("Navigation successful!")
except AssertionError:
print(f"Navigation failed! Expected {expected_url}, but got {actual_url}")
# Usage example
driver.get("https://www.example.com/login")
verify_navigation(driver, "example.com/login")
Working with Dynamic Pages
When working with dynamic pages, you might need to combine URL checking with handling pop-ups and alerts for more robust automation.
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
def wait_for_url_change(driver, old_url, timeout=10):
"""Wait for URL to change from the old URL"""
return WebDriverWait(driver, timeout).until(
lambda driver: driver.current_url != old_url
)
# Example usage
initial_url = driver.current_url
driver.find_element_by_id("submit-button").click()
wait_for_url_change(driver, initial_url)
print(f"New URL: {driver.current_url}")
Best Practices
Always ensure proper error handling when working with URLs in Selenium. Consider using proper logging practices for better debugging.
Conclusion
The current_url
property in Selenium is a powerful tool for web automation. By understanding how to use it effectively, you can create more robust and reliable automation scripts.
Remember to implement proper error handling and verification mechanisms when working with URLs to ensure your automation scripts are reliable and maintainable.