Showing posts with label LinkText. Show all posts
Showing posts with label LinkText. Show all posts

Monday 10 February 2014

How to Verify Broken Links using Selenium WebDriver

This program reads all link from a web page, sends open connection request to URL, checks for response code. Based on response code, broken link is identified & get printed on console.

import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.List;
import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.testng.annotations.Test;

public class Links_Broken {

    @Test
      public void saveAllLinks(){
          FirefoxDriver firefoxDriver = new FirefoxDriver(); //Starts Firefox browser
                  
          firefoxDriver.navigate().to("
http://google.co.in"); //opens Web Page
               
           List <WebElement>linksList = firefoxDriver.findElements(By.tagName("a")); // finds link  elements & stores in a list

//traverse each link from collection
          for(WebElement linkElement: linksList){
              String link =linkElement.getAttribute("href");
              if(link!=null){
                verifyLinkActive(link);
              }
          }
          firefoxDriver.quit(); // close Firefox browser
      }
          
      /**
       * This method verifies that link is active
       * @param link - link(URL)
       * @return - true/false
       */
       public void verifyLinkActive(String linkUrl){
          try {
             URL url = new URL(linkUrl);
             HttpURLConnection httpURLConnect=(HttpURLConnection)url.openConnection();
             httpURLConnect.setConnectTimeout(3000);
             httpURLConnect.connect();

             if(httpURLConnect.getResponseCode()==200){
                 System.out.println(linkUrl+" - "+httpURLConnect.getResponseMessage());
              }
            if(httpURLConnect.getResponseCode()==HttpURLConnection.HTTP_NOT_FOUND)  

             {
                 System.out.println(linkUrl+" - "+httpURLConnect.getResponseMessage() + " - "+                  HttpURLConnection.HTTP_NOT_FOUND);
              }
          } catch (MalformedURLException e) {
              e.printStackTrace();
          } catch (IOException e) {
              e.printStackTrace();
          } catch (Exception e) {
              e.printStackTrace();
          }
      }
}

Friday 3 January 2014

What are the element locators available with Selenium which could be used to locate elements on web page

There are mainly 5 locators used with Selenium –
1.       html id
2.       html name
3.       XPath locator
4.       Css locators
5.       DOM
6.       LinkText
7.       PartialLinkText
8.       Tagname

9.       Classname