Selenium WebDriver: Basic Browser Commands and Navigation in Java

Learn fundamental Selenium WebDriver commands for automating web browser actions using Java. This tutorial provides examples demonstrating how to open URLs, retrieve page information (title, source code), and close the browser, providing a foundation for web automation and testing.



Selenium WebDriver: Basic Browser Commands

This guide illustrates fundamental Selenium WebDriver commands for browser interaction using Java. These commands provide basic control over the browser window, enabling you to perform actions like opening URLs, getting page information (title, source code), and closing the browser. It is important to have a basic understanding of Java and Object-Oriented Programming to use Selenium WebDriver effectively.

Setting up the Environment

  1. Install Java: Make sure you have Java Development Kit (JDK) installed on your system and the JAVA_HOME environment variable is set correctly.
  2. Install Selenium WebDriver: Download the Selenium WebDriver JAR files (you'll need the correct version for your project) and add them to your project's classpath in Eclipse.
  3. Download ChromeDriver: Download the ChromeDriver executable appropriate for your operating system and version of Chrome. Place it in a directory, and note the path.
  4. Configure System Property: Configure the system property `"webdriver.chrome.driver"` to the path of your `chromedriver.exe` file.
  5. Setting ChromeDriver System Property
    
    System.setProperty("webdriver.chrome.driver", "path/to/chromedriver.exe");
                    

Example Test Script

This Java code demonstrates several basic Selenium WebDriver commands. It launches Chrome, navigates to a URL, retrieves and prints the page title and URL, and then closes the browser. Remember to replace `"path/to/chromedriver.exe"` with the correct path to your ChromeDriver executable.

Selenium WebDriver Example

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;

public class WebDriverCommands {
    public static void main(String[] args) {
        System.setProperty("webdriver.chrome.driver", "path/to/chromedriver.exe");
        WebDriver driver = new ChromeDriver();
        driver.get("https://www.example.com");
        String title = driver.getTitle();
        int titleLength = title.length();
        System.out.println("Length of the title is : " + titleLength);
        String url = driver.getCurrentUrl();
        System.out.println("URL: " + url);
        driver.close();
    }
}