getCurrentUrl()
Overview
In Selenium WebDriver, the getCurrentUrl()
method is used to retrieve the URL of the current page opened in the browser. It returns a string representing the URL of the current page.
Syntax
String currentUrl = driver.getCurrentUrl();
Usage
- Retrieving Current URL:
// Assuming 'driver' is an instance of WebDriver
String currentUrl = driver.getCurrentUrl();
System.out.println("Current URL: " + currentUrl);
2. Asserting Current URL:
// Assuming 'driver' is an instance of WebDriver
String expectedUrl = "https://www.example.com";
String currentUrl = driver.getCurrentUrl();
Assert.assertEquals(currentUrl, expectedUrl);
Example
public class GetCurrentURLExample {
public static void main(String[] args) {
// Set path to the ChromeDriver executable
System.setProperty("webdriver.chrome.driver", "path/to/chromedriver");
// Initialize ChromeDriver
WebDriver driver = new ChromeDriver();
// Open a webpage
driver.get("https://www.seleniums.com");
// Retrieve current URL
String currentUrl = driver.getCurrentUrl();
System.out.println("Current URL: " + currentUrl);
// Close the browser
driver.quit();
}
}
Importance
- Validation: It allows developers and testers to validate whether the expected page has been navigated to during test execution.
- Navigation: It aids in navigating through different pages of a web application based on the current URL.
Limitations
- Stale Element Reference Exception: In some cases, when a page undergoes a dynamic change after the initial load, using this method may result in a
StaleElementReferenceException
.
Conclusion
The getCurrentUrl()
method in Selenium WebDriver is a vital tool for retrieving and validating the URL of the current web page. Its simplicity and effectiveness make it a fundamental component in web automation testing.
Was this article helpful?
YesNo