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 = “http://www.google.com”;
driver = new FirefoxDriver();
driver.manage().window().maximize();
driver.get(baseUrl);
driver.findElement(By.id(“gbqfq”)).sendKeys(“selenium”);
driver.findElement(By.id(“gbqfb”)).click();
WebDriverBackedSelenium wbdriver = new WebDriverBackedSelenium(driver,”https://www.google.co.in/?gws_rd=cr&ei=LEJWUp3NIYbJrQfypYCIDg#q=SELENIUM”);
int linkcount = (Integer) wbdriver.getXpathCount(“//ol[@id=’rso’]/li/div/h3/a”);
System.out.println(linkcount);
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();
System.out.println(driver.getTitle());
driver.navigate().back();
}
} catch (ElementNotVisibleException enfe) {
System.out.println(“Element Not Visible Exception”);
} catch (ElementNotFoundException enf) {
System.out.println(“Element not found Exception”);
} finally {
driver.close();
driver.quit();
}
}
}

 

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”

 

Advertisements