Selenium WebDriver provides several navigation commands to move between web pages. The most commonly used ones are:
driver.get()driver.navigate().to()driver.navigate().back()driver.navigate().forward()
Below is a detailed explanation of each command with corrected example code.
1. driver.get()
driver.get() navigates to the specified URL and waits until the page is fully loaded before moving to the next line of code.
Key Points
- Most commonly used navigation method
- Waits for the page load to complete
- Accepts only a
StringURL
Example
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.testng.annotations.Test;
public class NavigationExample {
WebDriver driver;
@Test
public void navigation() {
driver = new ChromeDriver(); // Selenium 4.3+
driver.get("https://www.example.com");
}
}
2. driver.navigate().to()
driver.navigate().to() also navigates to a specified URL.
In practice, it behaves the same as driver.get() and also waits for the page to load.
Key Points
- Functionally similar to
driver.get() - Can accept a
Stringor aURLobject - Often used when working with back and forward navigation
Example
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.testng.annotations.Test;
public class NavigationExample {
WebDriver driver;
@Test
public void navigation() {
driver = new ChromeDriver(); // Selenium 4.3+
driver.navigate().to("https://www.example.com");
}
}
3. driver.navigate().back()
driver.navigate().back() moves the browser one step back in the browser history, similar to clicking the browser’s Back button.
Key Points
- Works only if there is a previous page in history
- Waits for the previous page to load
Example:
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.testng.annotations.Test;
public class NavigationExample {
WebDriver driver;
@Test
public void navigation() {
driver = new ChromeDriver(); // Selenium 4.3+
driver.get("https://www.google.com");
driver.navigate().to("https://www.amazon.com");
driver.navigate().back(); // Navigates back to Google
}
}
4. driver.navigate().forward()
driver.navigate().forward() moves the browser one step forward in the browser history, similar to clicking the browser’s Forward button.
Key Points
- Works only after using
back() - Waits for the forward page to load
Example
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.testng.annotations.Test;
public class NavigationExample {
WebDriver driver;
@Test
public void navigation() {
driver = new ChromeDriver(); // Selenium 4.3+
driver.get("https://www.google.com");
driver.navigate().to("https://www.amazon.com");
driver.navigate().back(); // Goes back to Google
driver.navigate().forward(); // Goes forward to Amazon
}
}