Sunday, January 31, 2016

GetAttributes, Title, Text and more.... in Selenium Webdriver

In this article, we will discuss how to extract data from elements or Page using Selenium Webdriver. Extracting attribute information and text of elements helps to validate elements have correct and expected attribute value or text.

Problem Statement of this article: 
  • How to get title of the page?
  • How to get text of an element?
  • How to get attribute value of element?

How to get title of the Page?


We can get title of the page as well as url of the current Page as shown  below: 
 WebDriver driver = new FirefoxDriver();  
 driver.navigate().to("https://www.google.com");  
 // We can get title of the page using driver.getTitle  
 System.out.println(driver.getTitle());  
 // We can get url of the page using driver.getCurrentUrl  
 System.out.println(driver.getCurrentUrl()); 

How to get text of an element in the Page?


We can get text of an element in the page using gettext() as shown in the code below:
One of the useful and important use of getText can be to get error messages displayed in page, where the class name of all the error message displayed in the page is same. It can be implemented as follows:
  • Identify the classname of the error message.
  • Using findelements, find collection of elements with class name.
  • Loop through the element collection and getText of each element.
 WebDriver driver = new FirefoxDriver();  
 driver.navigate().to("https://www.google.com");  
 WebElement elem = driver.findElement(By.id("gb_P gb_R"));  
 String message = elem.getText();  


How to use getAttribute to validate existence of an object and validating attribute properties?


Below code explains how to use getattribute to validate existence of element and extracting attribute value for the object.
 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.ie.InternetExplorerDriver;  
 
 
 public class FindAttributes {  
      static WebDriver driver;  
      @Test
  public void testing()
  { 
   driver = new FirefoxDriver();
   driver.navigate().to("https://www.google.com");
           //calling method to get names of all the links in the Page  
           textForObjectType("link");  
           // function to validate a particular object with particular text exists in the Page  
           ValidateObjectText("link", "About");       
           //   
      }  
      public static void textForObjectType(String strObj)  
       {  
           if(strObj.toLowerCase().trim().contentEquals("link"))  
           {  
                strObj = "a";  
           }  
           if(strObj.toLowerCase().trim().contentEquals("button"))  
           {  
                strObj = "button";  
           }  
     // Similarly can add object of other types. can use enum and switch for better control.
           List<WebElement> elemLink = driver.findElements(By.tagName(strObj));  
           int intLinksinPage = elemLink.size();  
           System.out.println(intLinksinPage);  
     // Loop to get attribute value of all the objects of the type in the page
           for (int i = 0;i<intLinksinPage;i++)  
           {  
                System.out.println("The name of the link " + (i+1) +" in the page is :- " + elemLink.get(i).getAttribute("text"));  
           }  
      }  
      public static void ValidateObjectText(String strObj, String ObjName)  
       {  
           if(strObj.toLowerCase().trim().contentEquals("link"))  
           {  
                strObj = "a";  
           }  
           if(strObj.toLowerCase().trim().contentEquals("button"))  
           {  
                strObj = "button";  
           }  
           List<WebElement> elemLink = driver.findElements(By.tagName(strObj));  
           int intLinksinPage = elemLink.size();  
           System.out.println(intLinksinPage);  
           for (int i = 0;i<intLinksinPage;i++)  
           {  
                if(elemLink.get(i).getAttribute("text").contentEquals(ObjName))  
                {  
                     System.out.println("Link exists in Page with text " + elemLink.get(i).getAttribute("text"));  
                }  
           }  
      }  
 }

Saturday, January 30, 2016

Xpath and css for Selenium Webdriver: Useful links and firepath

In one of the previous article, we discussed on how an element can be identified using different locators. Two of the generic element locators are using xpath and cssSelector.

Problem statement for this article:


  • What is XPath and CSS Selectors?
  • What are different tools to identify xpath or CSS for an element?
  • Common interview questions around xpath and CSS?
  • Common interview questions around xpath and CSS?
  • Some excellent reference on the web explaining how to create Xpath/CSS Selectors?

What is XPath and CSS Selectors?



Xpath
CSS Selectors
Stands for?
Xpath stands for XML Path language.
CSS stands for Cascading style sheets
Definition?
XPath is used to navigate through elements and attributes in an XML document.
CSS is a stylesheet language that describes the presentation of an HTML (or XML) document.
XPath is syntax defining parts of an XML document. Xpath uses path expressions to navigate in XML documents
CSS selectors are used to "find" (or select) HTML elements based on their element name, id, class, attribute,etc
We can traverse parent elements from child elements and vice versa using xpath.
CSS is native to browsers while Xpath is not.
Syntax
driver.findElement(By.xpath(xpathExpression));
driver.findElement(By.cssSelector(CSSExpression));
Which locator expression is more readable
In terms of readability , CSS are more readable
Which locator is comparably faster?
In various studies, it is mentioned CSS to be comparably faster than Xpath
Which locator is the best?
Since Id is believed to be unique for an element and can help uniquely identify an element, it is always best to use Id locator for object identification, if defined.

What are different tools to identify xpath or css Selector?


Using F12 or Inspect Element: 


In most of the browsers, option to inspect element is available on pressing F12. Below image shows how to inspect elements in chrome browsers to inspect an element. Similarly we can inspect element in IE browser and firefox browser.

Inspect Element in Chrome

 

Using Firepath and Firebug: 


Using FirePath with firebug, we can evaluate the css/xpath for an element as well as generate CSS/ xpath for an element as shown in the below image.FirePath is helpful with following features.

  • Generating xpath/css/sizzle for an element.
  • Evaluating xpath/css/sizzle matches elements in the html.
  • Viewing elements in the DOM tree structure.

Using Selenium IDE: 


When we record script on the AUT, all the elements recorded are identified based on element locators in the page. The test script recorded can be exported to different languages e.g: c#, Java.

The script generated can be used in tests also.


What is difference between "/" and "//" in X-path?

"/" is used to create ‘absolute’ path expressions from document node
"//" is used to create relative path expressions

Some excellent Reference materials available on understanding Xpath and CSS Selector are:


  • Understand how to create xpath and CSS Selector

Thursday, January 28, 2016

Javascriptexecutor to highlight element in Selenium Webdriver

The problem statement for this article is to highlight an element in webPage using Selenium Webdriver. Javascriptexecutor is useful concept in Selenium Webdriver with one of the use being highlighting an element in the page. You can further search down how to use javascriptexecutor in selenium webdriver to perform actions like send key operations, or executing some javascript operation:


Problem Statement:

  • What is Javascriptexecutor?
  • How to highlight an element using JavaScriptexecutor?



What is Javascriptexecutor?

  • JavaScriptexecutor is an interface providing mechanism to execute Javascript through selenium Webdriver.
  • JavaScriptexecutor is used for Javascript injection in the application
  • Through Javascript injection, we can perform different operation including sendkeys operation, clicking on an element or refreshing the html
  • There are two methods to execute javascript using Javascriptexecutor interface:
    • executeScript
    • executeAsyncScript

How to highlight an element using JavaScriptexecutor?

Below code shows how to inject javascript to highlight an element using javascriptexecutor:

 import java.io.File;  
 import org.openqa.selenium.By;
 import org.openqa.selenium.WebDriver;  
 import org.openqa.selenium.WebElement;  
 import org.openqa.selenium.ie.InternetExplorerDriver;  
 import org.openqa.selenium.JavascriptExecutor;  

 public class HighlightElem 
 {  
      static WebDriver driver;  
      public static void main(String[] args) throws InterruptedException 
   {  
           // Connect to the Internet driver server and create an instance of Internet explorer driver.       
           File file = new File("E:\\Testing\\IEDriverServer.exe");  
           System.setProperty("webdriver.ie.driver", file.getAbsolutePath());       
           try{  
                driver = new InternetExplorerDriver();  
           }  
           catch(Exception e)  
           {  
                driver=new InternetExplorerDriver();  
           }  
           //Navigate to the webpage and identify the element to be highlighted.Change the url to valid url  
           driver.navigate().to("https://seleniumbites.blogspot.com");  
     //provide the elemet property to be highlighted
           WebElement element = driver.finndElement(By.linkText("testing"));  
           //highlight the element  
            JavascriptExecutor js = (JavascriptExecutor) driver;  
           js.executeScript("arguments[0].setAttribute('style','border: solid 8px blue')", element);   
           Thread.sleep(2000);  
           js.executeScript("arguments[0].setAttribute('style', arguments[1]);", element, "");  
           element.click();            
      }  
 }