i

Selenium Step By Step Guide

Introduction to WebDriver – Code

Now we have got an understanding of WebDriver and its architecture. We can start using the same for the starting automation of web pages. As we have discussed in previous topics of WebDriver that WebDriver provides a channel of communication between tester and browser with the help of a tester’s code and browser driver.

 Let us start with a simple piece of code that opens the www.selflearning.io web page and fetches the element text from the "Testing" tab on the home page.

First, we must import all the required selenium packages to start with the first WebDriver code. Once packages are imported, we need to set the system property to define the browser driver path using the setProperty() method of System class.

Now we are ready to create a browser driver's object by taking reference to the WebDriver interface. Now the driver object can be used to navigate to the web page in the browser. Once we are landed on the web browser, we can locate the web element using the findElement() method of the SearchContext interface. We may discuss more on the findElement() method in detail later in this series.

findElement() method returns a WebElement type. Now we can use this returned value to fetch the text from this located element.

package SeleniumTest.SeleniumTest;

import org.openqa.selenium.By;

import org.openqa.selenium.WebDriver;

import org.openqa.selenium.WebElement;

import org.openqa.selenium.chrome.ChromeDriver;

public class WebDriverTest

{

    public static void main( String[] args )

    {

        System.setProperty("webdriver.chrome.driver","C:\\Users\\chromedriver.exe");

        WebDriver driver=new ChromeDriver();

        driver.get("https://selflearning.io/");

        WebElement element1=driver.findElement(By.xpath("/html/body/section[1]/div/div/section/div[1]/div[2]/ul/li[4]/a"));

        String eleText=element1.getText();

        System.out.println(eleText);

 

        driver.quit();

    }

}

This code opens the browser and lands to the www.selflearning.io page, and then it locates the “Testing” tab on selenium using the findElement() method of SearchContext interface. Once it locates the "Testing" tab element on the web page, we can fetch the text out of it using the getText() method of WebDriver.