Selenium Code Snippets -1

I have come across the below question in online forums about  How to click on each google link and get the page title using selenium. Though it is a small task but it involves constructing the xpath at run time and usage of WebDriverBackedSelenium and WebDriver implementation Classes.

Task :
  • Search for the word ‘Selenium’ in google
  • Click on the the link
  • Get the page title 
  • Navigate back and click on another search result
  • Repeat the above until clicking all the search results in the first page   
Here is the code Snippet for the above task 

import org.openqa.selenium.By;
import org.openqa.selenium.ElementNotVisibleException;
import org.openqa.selenium.WebDriverBackedSelenium;
import org.openqa.selenium.firefox.FirefoxDriver;
import com.gargoylesoftware.htmlunit.ElementNotFoundException;

public class GoogleLinks {
public static void main(String[] args) {
FirefoxDriver driver = null;
try {
String baseUrl = “”;
driver = new FirefoxDriver();
WebDriverBackedSelenium wbdriver = new WebDriverBackedSelenium(driver,””);
int linkcount = (Integer) wbdriver.getXpathCount(“//ol[@id=’rso’]/li/div/h3/a”);
for (int i = 1; i <= linkcount; i++) {
String Title = driver.findElement(By.xpath(“//ol[@id=’rso’]/li[” + i + “]/div/h3/a”)).getText();
System.out.println(“Clicking on Title :” + Title);
driver.findElement(By.xpath(“//ol[@id=’rso’]/li[” + i + “]/div/h3/a”)).click();
} catch (ElementNotVisibleException enfe) {
System.out.println(“Element Not Visible Exception”);
} catch (ElementNotFoundException enf) {
System.out.println(“Element not found Exception”);
} finally {


Note : You can mail me for your suggestions/discussions.

Excercise : Above Given snippet is for the Firefox browser try the same with the InternetExplorer, Chrome and other available browsers


“We are what we repeatedly do; Excellence,then, is not an act but a habit”