To start with selenium learning, the first step I suggest is to automate google. In this exercise i will try to show how to automate google.
The objective of this post is to automate a flow where steps are-
- open a firefox browser
- Navigate to google.
- in the search box type askqtp.
- Click on search
- list the links available in the search
- Click on the first link
- Read the title.
for this
//Normal imports
import java.util.List;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
public class ClickaLink {
public static void main(String[] args) {
//Creating the web driver
WebDriver fd=new FirefoxDriver();
//Step 1&2
fd.get("http:\google.com");
fd.manage().timeouts().implicitlyWait(20,TimeUnit.SECONDS);
//Step-3
fd.findElement(By.xpath("//input[@class='gbqfif']")).sendKeys("askqtp");
//step-4
fd.findElement(By.xpath("//*[@id='gbqfb']")).click();
WebElement box=fd.findElement(By.xpath("//*[@id='res']"));
//the center box in the results page that has all the links Step-5
List<WebElement>allLinks=box.findElements(By.xpath("//*[@id='rso']/li/div/h3/a"));
//xpath of the links displayed
System.out.println("Total Links -->" allLinks.size());
for(int i=1;i<allLinks.size();i++ ){
System.out.println(allLinks.get(i).getText());
//Step-6
allLinks.get(1).click();
//click on the first link that is displayed
}
}
By this code you will be able to click on the firstlink and automate google search. Hope this helps.