How to find a website rank using a particular keyword using selenium:

In this example, we are using selenium webdriver to find the web site position in the google results using a specific keyword. Script will iterate over first 10 pages and return you the result. You can modify the script in eclipse and can place your desired keyword to see the result.

Example:

package com;

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.chrome.ChromeDriver;
import org.testng.annotations.AfterTest;
import org.testng.annotations.Test;

public class findWebsiteRank {

static WebDriver driver;
String word = “selenium”;

@Test
public void findRank() throws Exception {
// chrome standalone server
System.setProperty(“webdriver.chrome.driver”,
“C:\\Users\\username\\Downloads\\chromedriver_win32\\chromedriver.exe”);
driver = new ChromeDriver();
driver.manage().window().maximize();

// scripts waits for 30 seconds for each command until the object appears on DOM
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);

// selenium command to open the web site
driver.get(“http://www.google.com”);

// sends the keyword in search bar
driver.findElement(By.name(“q”)).sendKeys(word);

// click submit
driver.findElement(By.name(“q”)).submit();

boolean flag = false;
// Below for loop is to search the website in first 10 google result pages.
for (int i = 1; i <= 10; i++) {
//System.out.println(“In page ” + i);
//System.out.println(“***************************************************************”);
// Below for loop is to search the url in the page
for (int j = 0; j <= 9; j++) {

List list = driver.findElements(By.tagName(“cite”));

if (list.get(j).getText().contains(“hackage”)) {
// Gets the page number
String str = driver.findElement(By.id(“resultStats”)).getText();
if(str.contains(“About”) && !str.contains(“page”)){
System.out.println(“Web site found. It exists at position “+(j+1)+” in “+ “page 1.”);
flag = true;
break;
}else{
String str2 = str.substring(0,7);
System.out.println(“Web site found. It exists at position “+(j+1)+” in “+str2);
flag = true;
break;
}
}

}
if (!flag) {
driver.findElement(By.linkText(“Next”)).click();
Thread.sleep(2);
}else{
break;
}

}

if(!flag){
System.out.println(“Web site does not present in the google first 10 search results.”);
}

}

@AfterTest
public void tearDown() {

driver.close();
}
}