DEV Community

Akshara Chandran
Akshara Chandran

Posted on

Steps To Create A Simple Web Driver Script

Below are the steps to create a simple Selenium WebDriver script in Java to automate a basic scenario of opening a web page and performing an action. Let's create a script to open the Google homepage, search for a term, and print the page title.

Step 1: Set Up Your Development Environment

Make sure you have the following set up:

  • Java Development Kit (JDK) installed
  • Integrated Development Environment (IDE) like IntelliJ IDEA or Eclipse installed
  • Selenium WebDriver Java bindings added to your project's dependencies

Step 2: Create a New Java Class

Create a new Java class in your project with a meaningful name (e.g., SimpleWebDriverScript).

Step 3: Write the Selenium WebDriver Script

Write the Selenium WebDriver script to automate the desired scenario. Here's the code to open Google, search for a term, and print the page title:

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

public class SimpleWebDriverScript {
    public static void main(String[] args) {
        // Set the path to the chromedriver executable
        System.setProperty("webdriver.chrome.driver", "/path/to/chromedriver");

        // Initialize the Chrome driver
        WebDriver driver = new ChromeDriver();

        // Open Google homepage
        driver.get("https://www.google.com");

        // Find the search box element
        WebElement searchBox = driver.findElement(By.name("q"));

        // Enter the search term
        searchBox.sendKeys("Selenium WebDriver");

        // Submit the search query
        searchBox.submit();

        // Print the page title
        System.out.println("Page title is: " + driver.getTitle());

        // Close the browser
        driver.quit();
    }
}
Enter fullscreen mode Exit fullscreen mode

Step 4: Run the Script

Run the script in your IDE. It will open Google, perform the search, print the page title, and then close the browser.

Note:

  • Make sure to replace "/path/to/chromedriver" with the actual path to your ChromeDriver executable.
  • You may need to include the Selenium WebDriver Java bindings (selenium-java.jar) in your project's dependencies.
  • Ensure that the version of ChromeDriver you use is compatible with the version of Google Chrome installed on your machine.

That's it! You've created a simple Selenium WebDriver script to automate a basic web scenario. You can extend this script to automate more complex interactions and scenarios as needed.

Top comments (0)