Capturing all Links on a Web Page and visiting those links using Web Driver

In general while testing any application we are facing a situation where we need to visit each link available on the Web Page. The Following script help floks how to handle it.

In the following example, I am going to visit 'www.google.com', captures all the links available on the page, visiting each link and coming back to home page.

importjava.util.List;
importorg.openqa.selenium.By;
importorg.openqa.selenium.WebDriver;
importorg.openqa.selenium.WebElement;
importorg.openqa.selenium.firefox.FirefoxDriver;

public class Links {

private static String homeWindow = null;
private static String[] links = null;
private static int linksCount = 0;

public static void main(String[] args) throws InterruptedException {

WebDriver driver = new FirefoxDriver();
driver.get("http://www.google.com/");
// Fllowing instruction extract all links from the webpage using selenium webdriver
List<WebElement> all_links_webpage = driver.findElements(By.tagName("a")); 
// Print total no of links on the webpage
System.out.println("Print total no of links on the webpage----------------------------------------------------");
linksCount = all_links_webpage.size();
System.out.println(linksCount); 

links= new String[linksCount];// Following instruction stores each link and Prints on console
System.out.println("Print Links-----------------------------------------------------------------------------------");

for(int i=0;i<linksCount;i++)

{
links[i] = all_links_webpage.get(i).getAttribute("href");
System.out.println(all_links_webpage.get(i).getAttribute("href"));
}
// Following instruction Return an opaque handle to this window that uniquely identifies it within this driver instance.
// This can be used to switch to this window at a later date
homeWindow = driver.getWindowHandle().toString(); 
// Visiting Each Link in on the Page

System.
out.println("Visiting Each Links------------------------------------------------------------------------"); 

for(int i=0;i<linksCount;i++)
{
driver.navigate().to(
links[i]);
Thread.sleep(3000);
driver.switchTo().window(
homeWindow);
}
driver.quit();
}
}