Showing posts with label WebDriver. Show all posts
Showing posts with label WebDriver. Show all posts

Wednesday 13 April 2016

How To Continue With Script Even If NoSuchElement Exception is Thrown

The Problem
If you selenium script fails to find element on page by provided locator, it throws NoSuchElement exception. NoSuchElement is an exception which is basically like crashing the program into a wall. Whenever this error comes, script execution gets stopped.

A Solution
As an automation developer, I can ensure uninterrupted script execution in two ways
1.       Using try/catch block

Let’s try to implement it in an example –

NoSuchElement error without Try/Catch Handling
     public static void main(String[] args) {
                                WebDriver driver = new FirefoxDriver();

                                driver.get("http://thebuddhatree.blogspot.in/");

                                driver.findElement(By.id("name")).click();
                }

Note – This program will generate error and script execution gets stopped if element with provided locator is not on page.

NoSuchElement error with Try/Catch Block

import org.openqa.selenium.By;
import org.openqa.selenium.NoSuchElementException;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;

public class NoSuchElementError {

                public static void main(String[] args) {
                                WebDriver driver = new FirefoxDriver();
                                driver.get("http://thebuddhatree.blogspot.in/");
                                try {
                                                driver.findElement(By.id("name")).click();
                                } catch (NoSuchElementException e) {
                                                System.out.println("In Catch Block");
                                }
                                System.out.println("Outside Block, resume executing other code");
                }
}

Note – This program will generate error but script execution will continue for remaining code.

2.       Using FindElements() method
Build into Selenium is an ability to search multiple elements using single action
findElements() method behavior can be summarized as follows  -

·         On Zero Match : return an empty list
·         On One Match : returns list of one WebElement only
·         On One+ Match : returns list with all matching elements

NoSuchElement error using FindElements()
public static void main(String[] args) {
                                WebDriver driver = new FirefoxDriver();
                                driver.get("http://google.in/");
                               
                                List <WebElement> elements  =driver.findElements(By.id("name"));
                                if (elements.size() == 0){
                                                System.out.println("Element Not Found");
                                }
                }
Expected Behavior
  • ·         Open the Browser
  • ·         Load the page
  • ·         Search for an element
  • ·         Fails to find element
  • ·         Script execution continued

Conclusion
Happy Learning

Please ask questions on Testing Forum, in case of any issues or doubts or questions.

Friday 19 February 2016

Introduction to Selenium WebDriver (Video Tutorial)

Selenium is browser automation tool & is used in wide range of web application. It can be implemented with many programming langauages, can run same script across browser & across operating systems.

This video helps you to learn following topics :


  1. Selenium Introduction
  2. Brief History 
  3. Selenium Tool Suite 
  4. Why Selenium 
  5. Note on Browser & Environment Support
  6. Advantage of WebDriver 
  7. Limitations of WebDriver
  8. How to choose the right Selenium Tool for your need 
  9. A short comparison of Selenium with QTP 
  10. Selenium WebDriver Overview 
  11. Define a Test Strategy for Automation 
  12. Pick a Programming Language 
  13. Choose an Editor 

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();
          }
      }
}

Sunday 29 December 2013

Selenium - How to highlight Element

It is always a good practice to highlight element before performing an operation. This helps us to know where the Selenium is currently focused or which element it is being executed.

There is no native way to do this, but because Selenium allows to execute JavaScript, it can be accomplished by  executing JavaScript method. Code is as follows -

import org.openqa.selenium.By;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.testng.annotations.Test;

public class HighLightElement {

WebDriver driver = new FirefoxDriver(); //Launch firefox browser

@Test
   public void highlightTest() throws InterruptedException {
driver.get("https://www.facebook.com/"); // open facebook site
driver.manage().window().maximize(); // maximize browser
WebElement emailField = driver.findElement(By.xpath("//*[@id='email']")); //get
                reference to email text field
Thread.sleep(2000); //Stop program execution for 2 seconds
highlightElement(emailField); // call to highlight method


/** Method which executes Java Script code to highlight page object */
public void highlightElement(WebElement element) { 
   for (int i = 0; i < 2; i++) 
  { 
JavascriptExecutor js = (JavascriptExecutor) driver; 
js.executeScript("arguments[0].setAttribute('style', arguments[1]);", element, "color: red; border: 5px solid red;"); 
js.executeScript("arguments[0].setAttribute('style', arguments[1]);", element, ""); 
     } 

}

Thursday 26 December 2013

Selenium - How to read URL of a link

Selenium code to get URL is as follows -

    1. Find the link as a Web Element using findElement() method

                      WebElement Lnk_URL =  driver.findElement(By.id("Lnk"));

    2. Get URL value using  "href" attribute
                      
                       String URL = Lnk_URL.getAttribute("href");

Thursday 19 December 2013

Selenium - Can we set the speed of the WebDriver

This piece of functionality does not exist in Selenium WebDriver.  WebDriver provides  implicit wait and explicit wait to make sure that conditions happen before you attempt an action.

Tuesday 3 December 2013

WebDriver - List of classes which implements

WebDriver  is an interface to use for testing which represents web browser. Following is list of classes which implements WebDriver interface:

1.       AndroidDriver
2.       AndroidWebDriver
3.       ChromeDriver
4.       EventFiringWebDriver
5.       FirefoxDriver
6.       HtmlUnitDriver
7.       InternetExplorerDriver
8.       IPhoneDriver
9.       IPhoneSimulatorDriver
10.     RemoteWebDriver
11.     SafariDriver

How to handle java script alert using WebDriver

WebDriver supports handling  JavaScript alerts using Alert interface.

          // Bring control on already opened alert
               Alert alert = driver.switchTo().alert();

          // Get the text/message of the alert or prompt
               alert.getText(); 
         
         // Click ok button of alert
              alert.accept();

         // Click Cancel button of alert

              alert.dismiss();

Friday 29 November 2013

Selenium TestNG - How to disable HTML Report Generation


Steps to disable TestNG default HTML Report generation is as follows - 
  1. Right Click on [Java Project] 
  2. Select [Properties] 
  3. Select [TestNG] 
  4. Select [Disable default Listeners]
  5. Click on [Ok] button
Note - This would work if you have installed TestNG as Eclipse plug-in.

Thursday 24 October 2013

Hybrid (Keyword + Data) Framework using Selenium WebDriver, JXL API, Log4J

Selenium Test Framework is a test automation framework, is developed using WebDriver, JXL API, LOG4J and MS Excel. It has following features -

  1. Hybrid (Keyword + Data) Framework
  2. Firefox browser testing
  3. Data Driven testing using XLS file, write one test method against multiple test data sets
  4. Well defined Tear Down feature, which provides ability to continue with test execution even in test failures/application crash
  5. HTML Test Report
  6. Test Script creation in XLS File
Visit link https://drive.google.com/file/d/0BypxAnZwsvAcYlVCajhMME5paWs/viewDrop a message if you want to download framework code.