I am automating a web application test suite and I need to verify that a redirect occurred successfully after a button click. How do I programmatically grab the current URL of the page from the browser instance using Python? I’ve seen some older methods, but I want to ensure I'm using the most efficient way to store the URL in a variable for assertions in my test scripts.
3 answers
To get the current URL in Selenium with Python, you simply need to access the current_url property of your driver instance. After you have initialized your driver (e.g., driver = webdriver.Chrome()) and navigated to a page, you can assign the URL to a variable like this: url = driver.current_url. This is a built-in property that returns a string representing the URL currently loaded in the active window or tab. It is highly recommended to use this property immediately after a command that triggers a redirect to ensure your test assertions are validating the correct state of the application.
Are you handling cases where the URL might change dynamically due to asynchronous JavaScript execution, and have you implemented an explicit wait to ensure the redirect is finished before you call the property? Sometimes Selenium retrieves the URL too quickly before the browser has finished updating the address bar, which can result in flaky tests where the assertion fails because it caught the previous URL.
It's just print(driver.current_url). It is one of the simplest commands in the library and works across all browser drivers like Chrome, Firefox, and Edge consistently.
I agree with Nancy, its simplicity is great. I also find it helpful to log this value whenever a test fails, as it provides an immediate visual cue in the logs of where the driver ended up when the error occurred.
Charles, that is a vital point for modern single-page applications. In these scenarios, I usually use WebDriverWait combined with the url_contains or url_to_be expected conditions. This forces the script to pause until the URL matches what we expect, rather than just grabbing whatever is there at that millisecond. It makes the automation much more resilient to network latency or slow server-side processing during the redirect phase.