Let's move from Beginner to Intermediate Level

Now that you know the ways to find the web elements and you have executed some basic programs, it is high time to move on to next level. Going forward we will be doing several hands-on exercises, so keep practising with your Eclipse.

Below is the code for that.

package seleniumBasics;

import org.openqa.selenium.By;

import org.openqa.selenium.WebDriver;

import org.openqa.selenium.firefox.FirefoxDriver;


public class LinkTextExample {

public static void main(String[] args) {

    // TODO Auto-generated method stub    

    try {

        System.setProperty("webdriver.gecko.driver", "C:\\Users\\Arul\\Desktop\\drivers\\gecko\\geckodriver.exe");  

        WebDriver driver = new FirefoxDriver();

        driver.navigate().to("http://www.google.com"); 

        driver.findElement(By.name("q")).sendKeys("Say Cheese!"); //search the term 

        driver.findElement(By.className("sbico-c")).click(); // clicking the search button

        Thread.sleep(2000); // waiting for two seconds for the page gets loaded

        driver.findElement(By.linkText("Say cheese - Wikipedia")).click(); // clicking on the link


    } catch (Exception e) {

        // TODO Auto-generated catch block

        e.printStackTrace();

    }


}

}

The above piece of code will search the given term and click on the wikipedia link. Let's a take a closer look at the code. If there are no comments next to the lines, we will not be able to identify the function of that line. In real time, the number of lines in the code will be huge. So we should follow a best practice to easily identify the web elements.

Let's re write the above code, to have a better understanding.

        WebDriver driver = new FirefoxDriver();

        driver.navigate().to("http://www.google.com"); 

        WebElement searchBox=driver.findElement(By.name("q"));
        searchBox.sendKeys("Say Cheese!");

        WebElement searchIcon=driver.findElement(By.className("sbico-c"));
        searchIcon.click();

        Thread.sleep(2000); // waiting for two seconds for the page gets loaded

        WebElement link=driver.findElement(By.linkText("Say cheese - Wikipedia"));
        link.click();

Best Practise:

Surround your code with try-catch bloack and give your web elements a relevant name, so that it will be easy for you when debugging.

results matching ""

    No results matching ""