To navigate to a particular URL in Selenium Java, you have two main options: using the get()
method or the navigate().to()
method. Both are widely used and supported by the Selenium WebDriver API.
1. Using driver.get(String url)
Method
Purpose: Loads the specified URL in the current browser window and waits for the page to fully load before proceeding.
Syntax:
driver.get("https://www.example.com");
Usage:
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
public class OpenUrlExample {
public static void main(String[] args) {
WebDriver driver = new ChromeDriver();
driver.get("https://www.example.com");
// ... your test code ... driver.quit();
}
}
2. Using driver.navigate().to(String url)
Method
Purpose: Also loads the specified URL, but through the Navigation
interface, which additionally supports navigating back, forward, and refresh actions.
Syntax:
driver.navigate().to("https://www.example.com");
Usage:
WebDriver driver = new ChromeDriver(); driver.navigate().to("https://www.example.com");
Notes and Differences
Method | Waits for Page Load | Maintains Browser History | Use Case |
---|---|---|---|
driver.get(url) | Yes | No | Simple loading/opening of a new URL |
driver.navigate().to(url) | Yes | Yes | When also using back/forward/refresh actions |
- Both methods are acceptable for simply loading a web page.
get()
is more commonly used for basic navigation, whilenavigate().to()
is used when you require advanced navigation (like going back/forward).
Common Mistake
- Always include the protocol (
http://
orhttps://
) in your URL to avoid exceptions.
Both methods are standard and supported; choose based on your needs for navigation history and test clarity.