Get Current URL in Selenium using Python: Tutorial

Related Product On This Page How to get Current URL in Selen

January 16, 2026 · 7 min read · Tool Comparison
Related Product

Get Current URL in Selenium utilize Python: Tutorial

is a well-established model that provides tools tailor-made for browser automation. When it comes to dexterously voyage several websites and web scrape material, or carrying out repetitive tasks Selenium is quintessential.

This tutorial illustrates a core method to get the current URL in selenium using python. Thecurrent_urlmethod is generally employed in cases where you require an intermediate URL from a redirect chain or motive to do a serial of navigations among different URLs.

Overview

Steps to get the current URL of a webpage in a browser expend Selenium Python:

  1. Install Selenium and set up WebDriver for your browser.
  2. Import Selenium and necessary modules in your Python script.
  3. Launch the browser using a WebDriver instance.
  4. Navigate to the target webpage using.get().
  5. Use .current_urlto retrieve the URL of the loaded page.
  6. Print or validate the URL as needed.
  7. Close the browser session after the test.

This method is omnipresent in most situations involving browser automation.

How to get Current URL in Selenium Webdriver using Python? (with Example)

To instantiate the usefulness of the current_url method, a basic exemplar imply sailing to a website using google chrome was performed. To further illustrate its import, piloting between multiple website while screen scraping information was also implemented. This example showcased how the current_url method is indispensable to verify correct pilotage with browser automation.

Before fulfill the code to sail to the URLhttps: //www.google.com, the following prerequisites are needed.

Pre-requisites

  • Set up a python environment.
  • Install Selenium. If you have conda or anaconda set up then using the pip package installer would be the almost efficient method for Selenium installation. Simply run this command (on anaconda prompt, or directly on the Linux depot):
    pip install selenium
  • Download the latest WebDriver for the browser you wish to use, or installwebdriver_managerby run the command:
    pip install webdriver_manager

Read More:

Using the Current URL method in Selenium to perform a URL check on google.com

Step 1:Import the needed parcel utilise the next command.

from selenium import webdriver from selenium.webdriver.chrome.service significance Service from webdriver_manager.chrome import ChromeDriverManager

Step 2: Use WebDriver managerto download the required WebDriver for your browser (currently,, IEDriver, OperaDriver, and EdgeChromiumDriver can be downloaded via this package).

First, the WebDriver manager package will search for the adaptation of the browser being utilise. Following this, it will ascertain your cache to see if the WebDriver is already present in your cache. If there is no WebDriver present, or an old edition is present, the package will download and save the latest version of the WebDriver.

Also Read:

In this instance google chrome is being utilise, therefore the WebDriver manager install the latest version of the ChromeDriver.

driver = webdriver.Chrome (service=Service (ChromeDriverManager () .install ()))

In the above command, theServiceobject inherits and sets the executable path as the location where the WebDriver has be saved following installation.

Step 3:You can too manually download the WebDriver for your respective browserhere. If you manually downloaded the WebDriver you will either need to place the driver on your system path (put the chromedriver.exe file in the same location as your python code file) or alternatively set your viable path as the fix of the WebDriver.

If your driver is on your system path:

from selenium import webdriver driver = webdriver.Chrome ()

Alternatively set practicable path as the location of webdriver:

from selenium meaning webdriver from selenium.webdriver.chrome.service importation Service ser = Service (r '' C: /Users/Asus/Downloads/chromedriver_win32/chromedriver.exe '') driver = webdriver.Chrome (service=ser)

For autonomous testing across multiple user personas, check out SUSATest — it explores your app like 10 different real users.

Following this, the chrome browser should open withdata;in the URL bar. When we attempt to get the current URL without fetching another URL, this is the URL, which will be obtained.

Step 4:Load your required URL usingget(), in this example, we fetched google.com from the WebDriver as seen below.

driver.get (`` https: //www.google.com '')

Step 5: Use the current_urlmethod to obtain the current URL from the driver and mark it.

get_url = driver.current_url print (`` The current url is: '' +str (get_url)) driver.quit ()

Performing URL checks with Current URL in Selenium expend Python

One can ensure precise piloting across multiple websites following the methodology of the code below.

from selenium importee webdriver from selenium.webdriver.chrome.service import Service from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support importee expected_conditions as EC from bs4 import BeautifulSoup significance codecs ser = Service (r '' C: /Users/Asus/Downloads/chromedriver_win32/chromedriver.exe '') driver = webdriver.Chrome (service=ser) driver.get (`` https: //www.google.com '') get_url = driver.current_url print (`` The current url is: '' +str (get_url)) # Redirect val = input (`` Enter a url: ``) wait = WebDriverWait (driver, 10) driver.get (val) wait.until (EC.url_to_be (val)) page_source = driver.page_source soup = BeautifulSoup (page_source, features= '' html.parser '') rubric = soup.title.text file=codecs.open ('article_titles.txt ', ' a+ ') file.write (title+ '' \n '') file.close () get_url = driver.current_url mark (`` The current url is: '' +str (get_url)) val = input (`` Enter a url: ``) expect = WebDriverWait (driver, 10) driver.get (val) wait.until (EC.url_to_be (val)) page_source = driver.page_source soup2 = BeautifulSoup (page_source, features= '' html.parser '') title = soup2.title.text file=codecs.open ('article_titles.txt ', ' a+ ') file.write (str (title) + '' \n '') file.close () get_url = driver.current_url mark (`` The current url is: '' +str (get_url)) driver.quit ()

Output

The current url is: https: //www.google.com/

Enter a url:
The current url is:

Enter a url:
The current url is:

The plan first openshttps: //www.google.com/. Then it inquire for a URL input; The URL of the clauseSelenium with Python: Getting Started with Automationis participate as input by the user. The rubric of the article on this page is so scraped and store in article_titles.txt as demo below.

Fetching the stimulation URL and scraping the title of the article.

Writing the article rubric into article_titles.txt.

Saving the article_titles.txt file.

Future another url for an article titledHow to download a file utilise Selenium and Pythonis participate as input. The plan grate the title of this article as well, appending it thearticle_titles.txtpapers as shown in the screenshots below.

Fetching the stimulant URL and scraping the title of the clause

Writing the article rubric into article_titles.txt.

Talk to an Expert

Difference between .current_url vs .get ()

It is crucial to distinguish betweendriver.current_urland driver.get ():

  • driver.get (URL):This command instruct the browser to sail to the specified URL and start page loading.
  • driver.current_url:This attribute returns the URL of the page currently loaded in the browser instance.

driver.get ()loads’a URL, whiledriver.current_url ‘ regain ’the URL of the currently load page.

Feature.get(url).current_url
FunctionNavigates to a new pageRetrieves the current page URL
Input/OutputTakes a URL string as inputReturns a URL string
Side EffectLoads a new pageNo side effect, just fetches data
Return ValueNoneString (the URL)

Example:

driver.get (`` https: //example.com '') # navigates to the page print (driver.current_url) # prints 'https: //example.com '

Read More:

Pragmatic Use Cases of Getting Current URL

Retrieving the current URL has numerous practical applications in Selenium automation:

  • Verifying Navigation:To ensure that clicking a link or submitting a form leads to the right page.
  • Handling Redirects:To track and control intermediate URLs in a redirection chain.
  • Session Management:To confirm that user sessions are maintained or alter as await after certain activeness.
  • Dynamic URL Handling:To evoke dynamic IDs or parameters from URLs for further use in tryout.
  • Error Logging:To include the current URL in error study to provide setting for test failures.

Read More:

Best Practices for Working with .current_url in Selenium

When working with current_url, consider these better practices:

  • Navigate before using.current_url: Always call.get()or complete navigation before accessing.current_url.
  • Use asseveration for validation: Combine .current_url with assertto check if the look URL is loaded.
  • Handle delayed redirects:Add to ensure the URL has update before substantiation.
  • Normalize URLs:When comparing URLs, consider normalizing them by removetrail stroke or URL argumentthat might vary but do not affect the page & # 8217; s content.
  • Log URLs on Failure:In case of test failures related to URL verification, log the actual current URL to aid in debugging.
  • Avoid Hardcoding Entire URLs:For dynamic constituent of URLs, useurl_contains ()or regular expressions for more pliant assertions.
  • Log for debugging:Print or log.current_urlduring tests to trace navigation issues.
  • Combine with contented checks: Use .current_urlalong with component or textbook checks for full validation.
  • Use in elision handling:Capture the current URL in error handling to understandthe failure context.
  • Be aware of single-page apps:In SPAs, watch for hash or question changes that affect.current_url.

Read More:

Why run Selenium tests on Real Devices?

Executing Selenium tests on real devices offers these vantage:

  • It improves test truth and reliability.
  • Real devices replicate actual user environments, including hardware, OS, and browser behaviour.
  • They help uncover issues related to performance, responsiveness, and device compatibility.
  • Real twist testing support establishment of mobile-specific features like touch, GPS, and orientation.

is a comprehensive testing tool that enable running Selenium Python tests across a wide range of real peregrine device and desktop browsers. This eliminates the complexities of managing an in-house twist lab and ensures tests are executed in environs that accurately symbolize end-user scenario. This conduct to more reliable test consequence and improved application quality.

Conclusion

The current_urlattribute in Selenium WebDriver with Python is a underlying tool for verify navigation, cover redirects, and ensuring the application behaves as expected. By realise its usage and adhering to best practices, automation scripts can be make more robust and reliable.

Tags
12,000+ Views

# Ask-and-Contributeabout this topic with our Discord community.

Related Guides

Automate This With SUSA

Upload your APK or URL. SUSA explores like 10 real users — finds bugs, accessibility violations, and security issues. No scripts needed.

Try SUSA Free

Test Your App Autonomously

Upload your APK or URL. SUSA explores like 10 real users — finds bugs, accessibility violations, and security issues. No scripts.

Try SUSA Free