Pages

Search This Blog

Loading...

Monday, February 9, 2015

what is Implicit, Explicit & Fluent Wait in Selenium Web driver and their difference.

Implicit Wait

By using Implicit wait we can tell Selenium that we would like it to wait for a certain amount of time before throwing an exception that it cannot find the element on the page. We should note that implicit waits will be in place for the entire time the browser is open. This means that any search for elements on the page could take the time the implicit wait is set for.



 WebDriver driver = new FirefoxDriver();
 driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
 driver.get("http://www.ebay.in/cat/mobiles/brand/Samsung");
 WebElement myDynamicElement = driver.findElement(By.id("myDynamicElement"));


Explicit Wait

It is more extendible in the means that you can set it up to wait for any condition you might like. Usually, you can use some of the prebuilt ExpectedConditions to wait for elements to become clickable, visible, invisible, etc.

driver.manage().timeouts().implicitlyWait(0, TimeUnit.SECONDS); //nullify implicitlyWait()
WebDriverWait wait = new WebDriverWait(driver, timeOutInSeconds);
element = wait.until(ExpectedConditions.visibilityOfElementLocated(by));

Fluent Wait

Each FluentWait instance defines the maximum amount of time to wait for a condition, as well as the frequency with which to check the condition. Furthermore, the user may configure the wait to ignore specific types of exceptions whilst waiting, such as NoSuchElementExceptions when searching for an element on the page..

FluentWait  wait = new FluentWait(driver).withTimeout(timeOutInSeconds,TimeUnit.SECONDS).pollingEvery(200,TimeUnit.MILLISECONDS)
.ignoring(NoSuchElementException.class);
        element = (WebElement) wait.until(ExpectedConditions.visibilityOfElementLocated(by));
package PageFactory; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.support.FindBy; import org.openqa.selenium.support.PageFactory; import org.openqa.selenium.support.ui.ExpectedConditions; import org.openqa.selenium.support.ui.FluentWait; import org.openqa.selenium.support.ui.WebDriverWait; import java.util.NoSuchElementException; import java.util.concurrent.TimeUnit; /** * Created by Niraj on 2/10/2015. */ public class ConceptPage { WebDriver driver; @FindBy(xpath="//input[@type='submit' and @title='See more']") WebElement btnSeeMore; @FindBy(xpath="//div[@class='itm'][21]//div[@class='itemttl']") WebElement thelement; public static final int DEFAULT_WAIT_4_PAGE = 12; public static final int DEFAULT_WAIT_4_ELEMENT = 15; public ConceptPage(WebDriver driver){ this.driver=driver; PageFactory.initElements(driver,this); } public void verify21stElement(){ WebElement webElement = waitforElementUsingFluent(driver, By.xpath("//div[@class='itm'][21]//div[@class='itemttl']//a"), 20);
 public void  verify21stElement(){
        WebElement webElement = waitForElement
(driver, By.xpath("//div[@class='itm'][21]//div[@class='itemttl']//a"), 20);

System.out.println("Element present : "+ webElement.getAttribute("href")); }


//Explicit wait function definition here...:

    public static WebElement waitForElement(WebDriver driver, final By by, int timeOutInSeconds) {
        WebElement element;
        try{
            //To use WebDriverWait(), we would have to nullify implicitlyWait().
            //Because implicitlyWait time also set "driver.findElement()" wait time.
            //info from: https://groups.google.com/forum/?fromgroups=#!topic/selenium-users/6VO_7IXylgY
            driver.manage().timeouts().implicitlyWait(0, TimeUnit.SECONDS); //nullify implicitlyWait()

            WebDriverWait wait = new WebDriverWait(driver, timeOutInSeconds);
            element = wait.until(ExpectedConditions.visibilityOfElementLocated(by));

            driver.manage().timeouts().implicitlyWait(DEFAULT_WAIT_4_ELEMENT, TimeUnit.SECONDS); //reset implicitlyWait
            return element; //return the element
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
    
//Fluent wait function definition goes here... 

    public static WebElement waitforElementUsingFluent(WebDriver driver, By by, int timeOutInSeconds){
        
        WebElement element;
       FluentWait  wait = new FluentWait(driver).withTimeout(timeOutInSeconds,TimeUnit.SECONDS).pollingEvery(200,TimeUnit.MILLISECONDS).ignoring(NoSuchElementException.class);
        element = (WebElement) wait.until(ExpectedConditions.visibilityOfElementLocated(by));
        return element;


    }

public void clickOnSeeMore(){
    btnSeeMore.click();
}
}


// Main test goes here...

package Selenium;
import PageFactory.ConceptPage;import PageFactory.HomePage;import org.openqa.selenium.WebDriver;import org.openqa.selenium.firefox.FirefoxDriver;import org.testng.annotations.BeforeTest;import org.testng.annotations.Test;
import java.util.concurrent.TimeUnit;
/** * Created by Niraj on 2/5/2015. */public class LoginWithPageFactory {
    WebDriver driver;
    LoginPage loginPage;
    HomePage homePage;
    @BeforeTest    public void setup(){
        driver = new FirefoxDriver();
        driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
        driver.get("http://www.ebay.in/cat/mobiles/brand/Samsung");
    }
    
    @Test(priority = 1)
    public void test_AJAX(){
        driver.get("http://www.ebay.in/cat/mobiles/brand/Samsung");
        ConceptPage conceptPage = new ConceptPage(driver);
        conceptPage.clickOnSeeMore();
        conceptPage.verify21stElement();

    }
    public void teardown(){
        driver.close();
        driver.quit();;

    }
}



Sunday, July 6, 2014

How to use preceding-sibling and following-sibling in xpath to find sibling nodes

How to use preceding-sibling and following-sibling in xpath to find sibling nodes


How to get all the preceding siblings of Apple

Xpath: "//ul/li[contains(text(),'Apple Mobiles')]/preceding-sibling::li"

This will give "Samsung Mobiles"

How to get all the following  siblings of Apple
Xpath: "//ul/li[contains(text(),'Apple Mobiles')]/following-sibling::li"

This will give all the preceding siblings ( Nokia Mobiles, HTC Mobiles, Sony Mobiles, Micromax mobiles)

There is trick to use preceding-sibling and following-sibling. Place matters when you use this at beginning it will give you reverse result
When you use preceding-sibling at beginning then it will give result  ( Nokia Mobiles, HTC Mobiles, Sony Mobiles, Micromax mobiles) instead of Samsung mobiles.

Xpath : "//li[preceding-sibling::li='Apple Mobiles']"

This will give Samsung mobiles.
when you use following-sibling at the beginning then it will give reverse result. Instead of giving all below nodes of Apple mobile this will give Samsung Mobiles.
Xpath: "//li[following-sibling::li='Apple Mobiles']"
Now the question is how to get all the nodes between Apple Mobiles and Sony Mobiles.

Xpath : "//ul/li[preceding-sibling::li='Apple Mobiles' and following-sibling::li='Sony Mobiles']"
This will return Nokia Mobiles and HTC Mobiles.

or
Xpath : "//ul/li[preceding-sibling::li[.='Apple Mobiles'] and following-sibling::li[.='Sony Mobiles']]"
Or You can use this in contains as well
Xpath: "//ul/li[preceding-sibling::li[contains(text(),'Apple Mobiles')] and following-sibling::li[contains(text(),'Sony Mobiles')]]"

How to find a sibling of a node

How to find a sibling of a node
There are many situation when we get difficulties to find the elements which do not have identification/attribute but their immediate siblings has some identification.




In above example if we want to get the text of H1 we can not use //h1 because there are more than one h1 on the page. If you see a and h1 both are siblings and children of div//[@class='title pad_btm15']
By using a sibling element's property we can find out his sibling. In above example we know id of a which is "mainContent" then we can get its sibling

Xpath:

"//a[@id='mainContent']/following-sibling::h1"


If you have more siblings with no attribute or no unique attribute like below.

then we can use the position us find out exact element using xpath:
Xpath:
Samsung Android Mobile
"//a[@id='mainContent']/following-sibling::h1[1]"

Nokia Android Mobile :
"//a[@id='mainContent']/following-sibling::h1[2]"

Which is the best way to locate an element?

We choose the method based on which gives the element in fastest way in all the browsers. Finding elements by ID is usually going to be the fastest option, because at its root, it eventually calls down to document.getElementById(), which is optimized by many browsers.
Finding elements by XPath is useful for finding elements using very complex selectors, and is the most flexible selection strategy, but it has the potential to be very slow, particularly in IE. In IE 6, 7, or 8, finding by XPath can be an order of magnitude slower than doing the same in Firefox. IE provides no native XPath-over-HTML solution, so the project must use a JavaScript XPath implementation, and the JavaScript engine in legacy versions of IE really is that much slower.
If you have a need to find an element using a complex selector, I usually recommend using CSS Selectors, if possible. It's not quite as flexible as XPath, but will cover many of the same cases, without exhibiting the extreme performance penalty on IE that XPath can.

How to use / and // in xpath

How to use / and // in xpath
Difference between / and //  
/

When / is used at the beginning of a path:

/div
it will define an absolute path to node "a" relative to the root. In this case, it will only find "a" nodes at the root of the XML tree.

//

When // is used at the beginning of a path:

//div

It will define a path to node "div" anywhere within the XML document. In this case, it will find "div" nodes located at any depth within the XML tree.

These XPath expressions can also be used in the middle of an XPath value to define ancestor-descendant relationships. When / is used in the middle of a path:

/div/a

Tt will define a path to node "a" that is a direct descendant (ie. a child) of node "div".

When // used in the middle of a path:

/div//a

It will define a path to node "a" that is any descendant (child node)  of node "div".

When we don't know the immediate parent of a child then we can use "." dot

will still find any node, "div", located anywhere within the XML tree. But, the XPath:

.//div

will find any node, "div", that is a descendant of the node . " In other words, preceding the "//" expression with a "." tells the XML search engine to execute the search relative to the current node reference.

Saturday, July 5, 2014

Difference between Selenium RC and Selenium Web Driver

Selenium RC
Selenium Web driver
It is easy and small API. These API’s are less Object oriented

As compared to RC, it is bit complex and large API. API’s are entirely Object oriented
Selenium RC is slower since it uses a JavaScript program called Selenium Core. This Selenium Core is the one that directly controls the browser, not you.
Web Driver is faster than Selenium RC since it speaks directly to the browser uses the browser’s own engine to control it.
Selenium Core, just like other JavaScript codes, can access disabled elements.
Web Driver interacts with page elements in a more realistic way. It interacts natively with browser application
Required to start server before executing the test script.
Doesn’t required to start server before executing the test script.
It is standalone java program which allow you to run Html test suites.
It actual core API which has binding in a range of languages.
Selenium RC cannot support the headless HtmlUnit browser. It needs a real, visible browser to operate on.
Web Driver can support the headless HtmlUnit browser.
It doesn’t supports of moving mouse cursors.
It supports of moving mouse cursors.
Selenium RC Has Built-In Test Result Generator. Selenium RC automatically generates an HTML file of test results. 
Web Driver has no built-in command that automatically generates a Test Results File.
It does not supports listeners
It supports the implementation of listeners
Selenium RC needs the help of the RC Server in order to do so.
web Driver directly talks to the browser
It does not support to test iphone/Android applications
It support to test iphone/Android applications
Selenium RC can support new browsers
It cannot readily support new browsers


Monday, September 12, 2011

How to select value in drop down using Webdriver

How to select values in drop down using Webdriver

This post will take you through the way you can select the value in a drop down. Webdriver does not have straight forward command "SELECT" which Selenium does.
In below example i will open home page of eBay India and search ipod in Consumer Electronic category. This page has a category drop down in which i will select
Consumer Electronics.



package com.web;
import java.io.File;
import java.util.List;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.firefox.FirefoxProfile;
import org.openqa.selenium.htmlunit.HtmlUnitDriver;
import org.openqa.selenium.ie.InternetExplorerDriver;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;


public class DropDownSelection {
 private static WebDriver driver=null;
 @BeforeTest
 @org.testng.annotations.Parameters({"BROWSER"})
 public void setup(String BROWSER){
  if(BROWSER.equals("FF")){
   File profileDir = new File("C:\\nir");
     FirefoxProfile profile = new FirefoxProfile(profileDir);
     profile.setPreference("general.useragent.override", "same user agent string as above");
     driver= new FirefoxDriver(profile);
   System.out.println("Broser Selected " + BROWSER);  
  }else if(BROWSER.equals("IE")){
   System.out.println("Broser Selected " + BROWSER);
   driver = new InternetExplorerDriver();
  }else if(BROWSER.equals("HU")){
   System.out.println("Broser Selected " + BROWSER);
   driver =new HtmlUnitDriver();
   
  } else
  {
   System.out.println("Broser Selected " + BROWSER);
   driver = new ChromeDriver();
  }

 }
 @Test
 public void testDropDownSelection() throws InterruptedException{
  
  driver.get("http://www.ebay.in");
  WebElement search = driver.findElement(By.name("_nkw"));
  search.sendKeys("ipod");

   List dd = driver.findElement(By.name("_sacat")).findElements(By.tagName("option"));
   for (WebElement option : dd) {
    System.out.println(option.getText());
    if ("Consumer Electronics".equalsIgnoreCase(option.getText())){
     option.click();
     break;
    }
   }
   driver.findElement(By.xpath("//input[@value='Search']")).submit();
   Thread.sleep(5000);
   driver.getPageSource().contains("results found");
  driver.quit();
 }

}




TestNG.xml
Using TestNG suite we will run the test case.



<?xml version="1.0" encoding="UTF-8"?>
<suite name="webDriver" parallel="tests">
 <listeners>
  <listener class-name="org.uncommons.reportng.HTMLReporter" />
  <listener class-name="org.uncommons.reportng.JUnitXMLReporter" />
 </listeners>
 <test name="WebDriverDemo Witn FF" preserve-order="true">
  <parameter name="BROWSER" value="FF" />
  <classes>
   <class name="com.web.DropDownSelection" />
  </classes>
  </test>

  </b>
</suite>



If above code does not work with you configuration just try another way given below.



 List  options = driver.findElements(By.tagName("option"));
  for (WebElement option : options) {
   if ("Consumer Electronics".equalsIgnoreCase(option.getText())){
    option.click();
   }
      }