How to Get Current URL in Selenium: Simple Syntax & Example
In Selenium, you can get the current URL of the browser using the
driver.current_url property in Python or driver.getCurrentUrl() method in Java. This returns the URL string of the page currently loaded in the browser controlled by Selenium.Syntax
The syntax to get the current URL depends on the programming language used with Selenium WebDriver.
- Python: Use
driver.current_urlto get the current page URL as a string. - Java: Use
driver.getCurrentUrl()method which returns the current URL string.
Here, driver is the WebDriver instance controlling the browser.
plaintext
Python: current_url = driver.current_url Java: String currentUrl = driver.getCurrentUrl();
Example
This example shows how to open a website and print the current URL using Selenium WebDriver in Python.
python
from selenium import webdriver from selenium.webdriver.chrome.service import Service from selenium.webdriver.chrome.options import Options # Setup Chrome options options = Options() options.add_argument('--headless') # Run browser in headless mode # Setup WebDriver service service = Service() driver = webdriver.Chrome(service=service, options=options) # Open a website url = 'https://example.com' driver.get(url) # Get current URL current_url = driver.current_url print('Current URL:', current_url) # Close the browser driver.quit()
Output
Current URL: https://example.com/
Common Pitfalls
- Trying to get the current URL before the page loads fully can return an old or empty URL.
- Using incorrect WebDriver instance or closing the driver before getting the URL causes errors.
- In Java, forgetting parentheses in
getCurrentUrl()leads to compilation errors. - Not handling exceptions when the browser session ends can cause test failures.
java
Wrong (Java): String url = driver.getCurrentUrl; // Missing parentheses Right (Java): String url = driver.getCurrentUrl();
Quick Reference
| Language | Syntax to Get Current URL |
|---|---|
| Python | driver.current_url |
| Java | driver.getCurrentUrl() |
Key Takeaways
Use driver.current_url in Python or driver.getCurrentUrl() in Java to get the current page URL.
Always ensure the page is fully loaded before retrieving the URL to get accurate results.
Remember to use parentheses with getCurrentUrl() in Java to avoid syntax errors.
Handle browser session properly to avoid exceptions when accessing the current URL.