Showing posts sorted by relevance for query selenium. Sort by date Show all posts
Showing posts sorted by relevance for query selenium. Sort by date Show all posts

How To Take Entire Page Screenshots In Selenium


capture full page screenshots using selenium

Normally, selenium can take screenshots using ‘TakeScreenshot’ interface. But many times selenium automation testers require full webpage screenshots for the purpose of reporting and validation. If we take screenshots using ‘TakeScreenshot’ interface we can only capture a view point of a webpage.

We can capture the default screenshot using the code written below.


 import java.io.File;  
 import java.util.concurrent.TimeUnit;  
 import org.apache.commons.io.FileUtils;  
 import org.openqa.selenium.OutputType;  
 import org.openqa.selenium.TakesScreenshot;  
 import org.openqa.selenium.WebDriver;  
 import org.openqa.selenium.chrome.ChromeDriver;  
 public class FullPage_Screenshot {  
   public static void main(String[] args) throws Exception {  
    System.setProperty("webdriver.chrome.driver", "D:/workspace/TestProject/src/chromedriver.exe");   
  WebDriver driver = new ChromeDriver() ;  
     driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);  
     driver.manage().window().maximize();    
     try{          
       File scrFile = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);   
       FileUtils.copyFile(scrFile, new File("D:\\screenShot1.png"));  
       System.out.println("Screenshot is captured and stored in your D: Drive");  
     }    
     catch (Exception e)  
     {   
       System.out.println("Error in loading the Google page");  
     }   
   }   
 }  
To take the screenshot of an entire page in selenium we need to take the help from javascript. Because ‘selenium java’ can execute javascript and javascript can interact with web browser very well, so taking help from javascript can be a very useful process.

 package capturescreenshot;  
 import java.awt.Graphics2D;  
 import java.awt.image.BufferedImage;  
 import java.io.ByteArrayInputStream;  
 import java.io.File;  
 import java.io.IOException;  
 import javax.imageio.ImageIO;  
 import org.openqa.selenium.JavascriptExecutor;  
 import org.openqa.selenium.OutputType;  
 import org.openqa.selenium.TakesScreenshot;  
 import org.openqa.selenium.WebDriver;  
 import org.openqa.selenium.chrome.ChromeDriver;  
 import org.openqa.selenium.remote.Augmenter;  
 /**  
 * Full Page Screenshot utility for Selenium Webdriver  
 *  
 * @author  
  */  
 public class ScreenShot {  
   private static int scrollTimeout = 0;  
   public ScreenShot(int timeout) {  
     scrollTimeout = timeout;  
   }  
   private static String getFullHeight(WebDriver driver) {  
     JavascriptExecutor js = (JavascriptExecutor) driver;  
     return js.executeScript("return document.body.scrollHeight").toString();  
   }  
   private static int getFullWidth(WebDriver driver) {  
     JavascriptExecutor js = (JavascriptExecutor) driver;  
     return ((Long) js.executeScript("return window.innerWidth",  
         new Object[0])).intValue();  
   }  
   private static int getWindowHeight(WebDriver driver) {  
     JavascriptExecutor js = (JavascriptExecutor) driver;  
     return ((Long) js.executeScript("return window.innerHeight",  
         new Object[0])).intValue();  
   }  
   private static void waitForScrolling() {  
     try {  
       Thread.sleep(scrollTimeout);  
     } catch (InterruptedException ignored) {  
     }  
   }  
   private static BufferedImage getScreenshotNative(WebDriver wd) {  
     ByteArrayInputStream imageArrayStream = null;  
     TakesScreenshot takesScreenshot = (TakesScreenshot) new Augmenter().augment(wd);  
     try {  
       imageArrayStream = new ByteArrayInputStream(takesScreenshot.getScreenshotAs(OutputType.BYTES));  
       return ImageIO.read(imageArrayStream);  
     } catch (IOException e) {  
       throw new RuntimeException("Can not parse screenshot data", e);  
     } finally {  
       try {  
         if (imageArrayStream != null) {  
           imageArrayStream.close();  
         }  
       } catch (IOException ignored) {  
       }  
     }  
   }  
   public static BufferedImage getScreenshot(WebDriver wd) {  
     JavascriptExecutor js = (JavascriptExecutor) wd;  
     int allH = Integer.parseInt(getFullHeight(wd));  
     int allW = getFullWidth(wd);  
     int winH = getWindowHeight(wd);  
     int scrollTimes = allH / winH;  
     int tail = allH - winH * scrollTimes;  
     BufferedImage finalImage = new BufferedImage(allW, allH, BufferedImage.TYPE_4BYTE_ABGR);  
     Graphics2D graphics = finalImage.createGraphics();  
     for (int n = 0; n < scrollTimes; n++) {  
       js.executeScript("scrollTo(0, arguments[0])", winH * n);  
       waitForScrolling();  
       BufferedImage part = getScreenshotNative(wd);  
       graphics.drawImage(part, 0, n * winH, null);  
     }  
     if (tail > 0) {  
       js.executeScript("scrollTo(0, document.body.scrollHeight)");  
       waitForScrolling();  
       BufferedImage last = getScreenshotNative(wd);  
       BufferedImage tailImage = last.getSubimage(0, last.getHeight() - tail, last.getWidth(), tail);  
       graphics.drawImage(tailImage, 0, scrollTimes * winH, null);  
     }  
     graphics.dispose();  
     return finalImage;  
   }  
   public static void EShot(WebDriver wd, String filename) {  
     try {  
       ImageIO.write(getScreenshot(wd), "PNG", new File(filename));  
     } catch (IOException e) {  
       System.out.println(e);  
     }  
   }  
   public static void main (String argc[]){  
     System.setProperty("webdriver.chrome.driver", "D:/workspace/TestProject/src/chromedriver.exe");  
     WebDriver driver = new ChromeDriver();  
     driver.get("https://en.wikipedia.org/wiki/India");  
      ScreenShot.EShot(driver, "d:/test" + ".png");  
      driver.quit();  
   }  
 }  

Selenium Installation process

Hi this is my first post on selenium . lets start with definition of selenium and then the installation process. My complete tutorial based on selenium java.  
how to install selenium

What is Selenium?

Selenium is a free (open source) automated testing suite for web applications across different browsers like google chrome, firefox IE,  opera and safari .It also run on different OS like windows, Linux, mac. It is quite similar to UFT (HP) previously it was QTP, but selenium works only on web application


Installation : 

1.  Install java sdk  from oracle  website on your computer. 

Download java sdk based on your OS and the architecture like 32 bit or 64 bit . 

2. Install the java.  

3. Set the java path.  Please follow the instruction how to set the java path in your system. 

4.  Download selenium jars from here

      ii. java

5.  Extract java jars.  

6 . Download JAVA IDE like eclipse . In my selenium tutorial I will use eclipse because it is easy to use.  You can download eclipse from here

7. Create a new project through File > New > Java Project. Name the project as "newproject".

8.A new pop-up window will open enter details as follow

     i. Project Name
     ii. Location to save project
     iii. Select an execution JRE
     iv. Select layout project option
     v. Click on finish button

9. Now selenium WebDriver's into Java Build Path

In this step,

i.   Right-click on "newproject" and select Properties.
ii.  On the Properties dialog, click on "Java Build Path".
iii. Click on the Libraries tab, and then
iiv. Click on "Add External JARs.."

Now your project is ready to use as a selenium test.

Thanks to read my blog . Please let me know if you have any query on selenium installation process . I will try to solve the query.


In my next tutorial I will explain selenium locators and how to user different locator in script. 





  

Dynamically changing proxy in browsers with Selenium webdriver



Dynamically changing proxy in different browsers with Selenium webdriver

how to change the proxy in selenium


The earliest and recommended way to change the proxy settings is to change the proxy manually from the browser settings. But in the automation perspective manual intervention is not a good approach.  So what we need to do is to change the proxy settings in runtime. Now, the question is why is it required to change the proxy. The answer is simple. While trying to access some secure application a proxy is needed because otherwise it is impossible to access that very application. Or, while working on a secure environment where every traffic must go through a specific proxy, providing a separate proxy is absolutely necessary to access the application.

Setting up the proxy manually from a web browser



setting up proxy using selenium
In the above image it can be seen that there is a section for the proxy server.  Now the required process is to set the proxy server in Address field and the port number in the port field.
How to change the proxy settings in runtime.

There are several ways to change the proxy settings in runtime and creating object of proxy class is one of them.

Chrome and Internet explorer share the same proxy settings, so same line of code will work for both of the browsers. But when it comes to Firefox there are some changes in that line of code. The Firefox Version 48 and the newer versions require GeckoDriver and a different setup for adding proxy. As  per seleniumhq
“Firefox maintains its proxy configuration in a profile. You can preset the proxy in a profile and use that Firefox Profile or you can set it on profile that is created on the fly as is shown in the following example. With GeckoDriver the proxy has to be passed through the required capabilities.”



Proxy setup for IE,Chrome and Firefox(upto 47)
 String PROXY = "abc.xyz.com:8060";  
 org.openqa.selenium.Proxy proxy = new org.openqa.selenium.Proxy();  
    proxy.setHttpProxy(PROXY)  
      .setFtpProxy(PROXY)  
      .setSslProxy(PROXY);  
 DesiredCapabilities cap = new DesiredCapabilities();  
 cap.setCapability(CapabilityType.PROXY, proxy);  

Proxy setup for Firefox(version 48+)

 String PROXY = "localhost";  
 int PORT = 8080;  
 com.google.gson.JsonObject json = new com.google.gson.JsonObject();  
 json.addProperty("proxyType", "MANUAL");  
 json.addProperty("httpProxy", PROXY);  
 json.addProperty("httpProxyPort", PORT);  
 json.addProperty("sslProxy", PROXY);  
 json.addProperty("sslProxyPort", PORT);  
 DesiredCapabilities cap = new DesiredCapabilities();  
 cap.setCapability("proxy", json);  
 GeckoDriverService service =new GeckoDriverService.Builder(firefoxBinary)  
  .usingDriverExecutable(new File("path to geckodriver"))  
  .usingAnyFreePort()  
  .usingAnyFreePort()  
  .build();  
 service.start();  
 // GeckoDriver currently needs the Proxy set in RequiredCapabilities  
 driver = new FirefoxDriver(service, cap, cap);  

There is the complete code for chrome browser

 package com.test;  
 import java.io.File;  
 import java.util.concurrent.TimeUnit;  
 import org.apache.commons.io.FileUtils;  
 import org.openqa.selenium.OutputType;  
 import org.openqa.selenium.TakesScreenshot;  
 import org.openqa.selenium.WebDriver;  
 import org.openqa.selenium.chrome.ChromeDriver;  
 import org.openqa.selenium.remote.CapabilityType;  
 import org.openqa.selenium.remote.DesiredCapabilities;  
 public class FullPage_Screenshot {  
   public static void main(String[] args) throws Exception {  
    String PROXY = "abc.xyz.com:8060";  
    org.openqa.selenium.Proxy proxy = new org.openqa.selenium.Proxy();  
    proxy.setHttpProxy(PROXY)  
      .setFtpProxy(PROXY)  
      .setSslProxy(PROXY);  
    DesiredCapabilities cap = new DesiredCapabilities();  
    cap.setCapability(CapabilityType.PROXY, proxy);  
    //WebDriver driver = new InternetExplorerDriver(cap);  
    System.setProperty("webdriver.chrome.driver", "D:/workspace/TestProject/src/chromedriver.exe");   
  WebDriver driver = new ChromeDriver(cap) ;  
     driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);  
     driver.get("https://www.google.com");  
     driver.manage().window().maximize();    
     driver.quit();  
   }   
 }  

How to use chrome headless using selenium

How to use chrome headless using selenium

How to use chrome headless using selenium  


A headless browser is a kind of web browser which has no user interface, In other words,  a browser, that access web pages but doesn’t show them to any human being. They’re actually used to provide the content of web pages to other programs. 



Why is that useful?



A headless browser is a great tool for automated testing and server environments where you don't need a visible UI shell. For example, you may want to run some tests against a real web page, create a PDF of it, or just inspect how the browser renders an URL.

Now Chrome also supports headless feature from version 59 .  

Right now, Selenium opens a full instance of Chrome. In other words, it's an automated solution but not completely headless. However, Selenium could use --headless in the future.


There are few bugs  in new chrome driver so we need to use 2 chromeOptions to use headless Chrome in selenium  

Here is code for chrome headless  in windows system 

 import org.junit.Assert;  
 import org.junit.Test;  
 import org.openqa.selenium.By;  
 import org.openqa.selenium.WebDriver;  
 import org.openqa.selenium.chrome.ChromeDriver;  
 import org.openqa.selenium.chrome.ChromeOptions;  
 import org.openqa.selenium.support.ui.ExpectedConditions;  
 import org.openqa.selenium.support.ui.WebDriverWait;  
 import java.io.IOException;  
 public class HeadlessChrome  
 {  
  @Test  
  public void createChromeDriverHeadless() throws IOException  
  {  
    ChromeOptions chromeOptions = new ChromeOptions();  
    System.setProperty("webdriver.chrome.driver", "C:\\Users\\anjan\\Desktop\\cucmber\\chromedriver_win32\\chromedriver.exe");  
    chromeOptions.addArguments("--headless");  
    chromeOptions.addArguments("--disable-gpu");  
    WebDriver Driver = new ChromeDriver(chromeOptions);  
    Driver.navigate().to("https://www.facebook.com");  
    WebDriverWait waitForUsername = new WebDriverWait(Driver, 5000);  
    waitForUsername.until(ExpectedConditions.visibilityOfElementLocated(By.id("email")));  
    Driver.findElement(By.id("email")).sendKeys("tomsmith");  
    Driver.findElement(By.id("loginbutton")).click();  
    WebDriverWait waitForError = new WebDriverWait(Driver, 5000);  
    waitForError.until(ExpectedConditions.visibilityOfElementLocated(By.id("email")));  
    Assert.assertTrue(Driver.findElement(By.id("loginbutton")).getText().contains("Log In"));  
    Driver.quit();  
  }  
 }  

How to create maven project in eclipse for selenium



how to create maven project in eclipse for selenium

How to create maven project in eclipse for selenium

In my earlier post I have discussed about maven tool on automation front.  I have also discussed about whats is POM and why we use maven tool for java project .  In this post I will create one sample selenium project using maven. Before creating the maven project we need to download and install maven.  I am assuming you  have JAVA and eclipse IDE installed in your machine.

Prerequisite 

  1. Download Maven LINK.
  2. Install maven .
  3. Add M2_HOME and MAVEN_HOME in the Windows environment, and point it to your Maven folder.
  4. Add Path
  5. Verify
  6. Install maven plugin in your eclipse.  
1. Download Maven

You can download maven from the below link.  
2. Install maven .

There is no installation file. You just need to download the archive file and extract in tour hard drive. Assuming you have extract the folder in C:\Program Files\Apache\maven

maven folder after unzip


3. Add M2_HOME and MAVEN_HOME

Add M2_HOME and MAVEN_HOME variable in windows environment.

M2_HOME should be C:\Program Files\Apache\maven
MAVEN_HOME should be C:\Program Files\Apache\maven


4.  Add Path
You need to Update PATH variable, append Maven bin folder – %M2_HOME%\bin, so that you can run the Maven’s command everywhere.

5. Verify

Run the below command to know that maven installed and configured in your system properly or not. If you see the version and maven home after executing the command it means maven configured properly. 

Maven command 

mvn –version in the command prompt/cmd

6. Install maven plugin in your eclipse. 

You need to download eclipse maven plugin from eclipse marketplace.
Maven plugin for eclipse

Or if you really don't want to do this above mentioned steps to configure maven in your system there is another simple way to solve this problem.You just need to download maven enabled eclipse from the eclipse website. Here is the link below for eclipse luna with eclipse integration .


Till now we have configured the maven environment.  Now we will create selenium project with maven 

Step 1:  Create maven project from eclipse IDE 

Go to File -> Project -> Maven -> Maven Project 

Next screen will ask for your project location where you want to create the project.  You can use Default Workspace location. 


Step 2:  Select Archetype 

 In the next screen, It will ask you to select an Archetype. Depending on the type of project that you are working, you need to choose the archetype


Step 3:  Enter a group id for the artifact

Now you need to enter a group id for the artifact, artifact id ,version and package,
We will input as shown in the below image. Version number will be by default 0.0.1-SNAPSHOT


Step 4: Finish step

After clicking finish button the maven project will be created with maven structure. It will create one sample POM also.

Sample POM look like this

Step 4: Edit POM file and add selenium dependency 

Copy the selenium dependency XML from maven central. or you can also get the XML from selenium org web site


  1. selenium website  -  LINK http://docs.seleniumhq.org/download/maven.jsp


    2. maven central   - LINK


Edit the POM XML file for the project and add the selenium dependency 



Step 6: Save the project using CTRL+S

Once you save the project it maven start building the project. Means maven start pulling all required dependency  from the maven central.

You can build the project using build maven command. you can set the goal as compile.


Step 7:  Navigate to src/test/java 

If you navigate to src/test/java folder , you will see there is class call AppTest . You can use this call for writing test case or you can create different class file per your requirement. 

I have created separate  class file called "TestCode" under src/test/java folder. I am using junit for writing test.  If you look into the POM file , you will see junit is already added in the dependency.  If you observe junit is not added in your POM file then you need to add the dependency for junit. 



Step 8:  Run the Junit test

Run the test in junit you will see chrome will open and navigate to facebook page . In my previous post I have mentioned how to open chrome in selenium. 


download maven selenium projectDownload sample maven selenium  Project 


How to Run Webdriver in chrome browser?


how to open chrome in selenium



How to Run Webdriver in chrome browser?


To run the Chrome browser in selenium we need to download the Chrome driver separately from the below link
https://sites.google.com/a/chromium.org/chromedriver/.  It will provide you with the latest driver and it’s nothing but an ‘.exe file’.  You just need to download it and unzip the file in a proper location.

I can assume that you already know how to install selenium and setup a selenium project. If you do not know how to then you can refer to my previous post selenium installation process for the purpose of setting up a selenium project.

The next thing you need to do is to set the property for Chrome driver and specify its location via the property ‘webdriver.chrome.driver’ as stated below.


System.setProperty("webdriver.chrome.driver", "pathofchromedriver");


For the next part what you need to do is to provide the path of the Chrome driver. In my case, my Chrome driver is located in ‘D:/workspace/TestProject/src/chromedriver.exe’ . Here,yYou need to provide your Chrome driver path at "pathofchromedriver"; and after that, you need to initialize the chormeDriver


WebDriver  driver = new ChromeDriver();


Open the browser using the ‘get’ method

driver.get(https://www.google.com");

Let’s try to open a Chrome browser using selenium webdriver.
 package com.test;  
 import org.openqa.selenium.WebDriver;  
 import org.openqa.selenium.chrome.ChromeDriver;  
 public class SeleniumMethod {  
  static WebDriver driver;  
  public static void main(String argc[]){  
  openURL();  
  }  
  public static void openURL(){  
  System.setProperty("webdriver.chrome.driver", "D:/workspace/TestProject/src/chromedriver.exe");   
  driver = new ChromeDriver() ;  
  driver.get("https://www.google.com");  
  }  
 }  

How to access web table element in selenium webdriver


How to access web table element in selenium web driver

There are 2 types of HTML table possible in the web.
  • Static web table.
  • Dynamic web table. 
Static web table:  Normally static tables are static in nature, means a number of column and row is fixed, it will never increase in runtime and data inside the each cell is also fixed.
Dynamic web table:  It is just opposite of static web table, here row, column and cell data could be not fixed or we can say dynamic.  It will change at runtime. 


We need to follow few steps to retrieve data from web table 

  1. We need to uniquely identify table object.
  2. Count number of rows present in the table.
  3. Count number of column present in each row. 
  4. Get the value from each cell.  

Step 1. We need to uniquely identify table object

Now we can start with the below table. We need to identify the web table uniquely. 

how to find element from web table using selenium

how to find element from web table using selenium
Here we can see there an id for that highlighted table.  The id is “ customers “.  We know how to identify the web element using XPath or other selenium locators, you can refer my previous post also. 

XPath for this table object

//*[@id="customers"]

Java code 

driver.findelement(By.xapth(“//*[@id="customers"]”);


Step 2: Count Number of rows present in the table.


In HTML table row denoted as <tr>. So we need to count the number of <tr> present under the table. 
We can directly count the number of rows is available on the table. 

how to find element from web table using selenium

XPath for row count
//*[@id='customers']/child::*/child::tr

Above XPath will return 7 element




Java code 

int rowCount = driver.findElements(By.xpath("//*[@id='customers']/child::*/child::tr")).size()

Step 3: Count Number of column present in each row.

Now we need to iterate each row and find out how many columns are there for that row. 

how to find web element from web table using selenium

Xpath for column count for first row (except header)
//*[@id='customers']/child::*/child::tr[1]/child::td
Above XPath will return 3 <td> tag

Java code  

int columnCount = driver.findElements(By.xpath//[@id='customers']/child::*/child::tr[1]/child::td")).size()

Step 4: Get the value from each cell.

Java code

driver.findElement(By.xpath("//*[@id='customers']/child::*/child::tr["+row+"]/child::td["+column+"]"));
element.getText()

Complete java code to iterate each row and column and print the value 

 public static void main(String argc[]){  
 System.setProperty("webdriver.chrome.driver","D:/workspace/TestProject/src/chromedriver.exe");   
 driver = new ChromeDriver() ;  
 driver.get("https://www.w3schools.com/html/html_tables.asp");  
 int rowCount = driver.findElements(By.xpath("//*[@id='customers']/child::*/child::tr")).size();  
 for (int i=1;i<=rowCount;i++){  
   int columnCount =  driver.findElements(By.xpath("//*[@id='customers']/child::*/child::tr["+i+"]/child::td")).size();  
    for(int j=1;j<=columnCount;j++){  
      WebElement element =  driver.findElement(By.xpath("//*[@id='customers']/child::*/child::tr["+i+"]/child::td["+j+"]"));  
      System.out.println(element.getText()+ "  ");  
    }  
   System.out.println();  
  }   
   driver.quit();  
 }  

Selenium Locators

Very basic question what is the locator in selenium, Locators allows us to find elements on a page that can be used in our test.  Actually we need to uniquely identify one element from HTML page where we can do operation like click, select, sendKeys etc.
Selenium webdriver provide us various mechanism to uniquely identify one element from HTML.

1.  Locate elements by ID
2.  Locate elements by Name
3.  Locate elements by Link
4.  Locate elements by Xpath
5.  Locate elements by Css
6.  Locate elements by DOM
7.  Locate elements by PartialLink

Before starting we should begain by making sure that we have all the relevant application installed. While there are not fullproof , they will give us clue how to construct the locator for our test page.


Firefox browser:

1. Firebug: This is a Firefox addon and it allows developer to find elements on the page.

Firebug is available in firefox addon section


firebug install


2. Firepath :

Firepath is available in Firefox addon section.

IE browser:

1. IE Developer tool: This is in build feature for IE ,we can launch by pressing F12.

Chrome:

1. Google chrome developer tool: Like IE this is also in build tool for chrome. By  pressing F12 we can use this tool. We can generate Xpath ,css path using this tool.


find xpath in chrome



copy xpath in chrome
Xapth or css path generation









Now start with locate element by ID

On web application element should have an ID for all there controls on the page. ID should be the unique for that page.

How to find element by ID in selenium 


selenium locators
In the  image you will find the ID of the google search text box.  id="lst-ib".
ID is unique for this page.

Now we will write down java selenium code to uniquely identify the web element (In selenium all web component is a web element) and we will operate on this web element.

Here we are assuming we using Firefox browser
WebDriver driver = new FirefoxDriver();
WebElement we = driver.findElement(By.id("st-ib"));
we.sendKeys("selenium:);

In my next post I will cover below items

1.  Locate elements by Name
2.  Locate elements by Link
3.  Locate elements by Xpath

How to highlight elements in WebDriver during runtime

How to highlight elements in WebDriver during runtime

In web automation-testing, element highlighter plays a very important role. It helps to track the exact step to be performed.  UFT/QTP like testing tool is capable to highlight an element in run time because you will get this feature inbuilt with this tool. In Selenium there is no such feature available so we need to write our own code to highlight element.

  
Highlighting element is also useful for debugging the code.One way to know steps being performed in the browser is to highlight the web page elements.

The core to use "JavaScriptExecutor" to inject javascript in your application and change the CSS for the element, like create a border for the element. 

Sample code 
 JavascriptExecutor js=(JavascriptExecutor)driver;   
 js.executeScript("arguments[0].style.border='4px groove red'", Element);  

Explanation  

Arguments[0].style.border:- this script is injecting the CSS style tag into the element and making its border settings with a 4px wide red line with groove look.

Element: - This is the element around which border will be drawn.

I am creating a method which could be reusable for highlighting the test element. 

Element Highlight method 


 public void HighlightElement(WebDriver driver, WebElement elm){  
           try{  
                JavascriptExecutor js=(JavascriptExecutor)driver;   
                js.executeScript("arguments[0].style.border='4px groove red'", elm);  
          Thread.sleep(1000);  
          js.executeScript("arguments[0].style.border=''", elm);  
           }catch(Exception e){  
                System.out.println(e);  
           }  
      }px groove red'", email);  


Video



Complete code


 package com.selenium.sampleseleniumproject;  
 import org.testng.annotations.Test;  
 import org.openqa.selenium.By;  
 import org.openqa.selenium.JavascriptExecutor;  
 import org.openqa.selenium.WebDriver;  
 import org.openqa.selenium.WebElement;  
 import org.openqa.selenium.chrome.ChromeDriver;  
 public class AppTest3 {  
      protected WebDriver driver;  
      @Test  
      public void Highlight() throws InterruptedException {  
           System.setProperty("webdriver.chrome.driver",  
                     "C:\\Users\\anjan\\Desktop\\cucmber\\chromedriver\\chromedriver.exe");  
           driver = new ChromeDriver();  
           driver.get("http://www.faceboo.com");  
           driver.manage().window().maximize();  
           WebElement email = driver.findElement(By.xpath("//*[@id='email']"));  
           WebElement pass = driver.findElement(By.xpath("//*[@id='pass']"));  
           HighlightElement(driver, email);  
           email.sendKeys("[email protected]");  
           HighlightElement(driver, pass);  
           pass.sendKeys("password");  
           // close browser  
           driver.close();  
      }  
      public void HighlightElement(WebDriver driver, WebElement elm) {  
           try {  
                JavascriptExecutor js = (JavascriptExecutor) driver;  
                js.executeScript("arguments[0].style.border='4px groove red'", elm);  
                Thread.sleep(1000);  
                js.executeScript("arguments[0].style.border=''", elm);  
           } catch (Exception e) {  
                System.out.println(e);  
           }  
      }  
 }  

How to Identify Web Elements Using Selenium Xpath and name

How to find element by Name in selenium

Elements do not necessarily have ID attributes on all of them. Elements can be have names that we can use to locate them uniquely. 



how to use chrome XPath isnpector
In the  image you will find value of the name attribute  of the google search text box is "q".
name is unique for this page.

Now we will write down java selenium code to uniquely identify the web element

WebDriver driver = new FirefoxDriver();
WebElement we = driver.findElement(By.name("q"));

Now we can write down the values in the search text box like below method.

we.sendKeys("selenium:);

How to find element by Xpath in selenium

Before start this topic we need to know what is xpath and how to build the xpath. Most of the time we are using xpath generator tool like Firebug , chrome developer tool ,but sometime we can not solely depend on those tool . We need to design xpath manually to overcome the complex situation.

If we look the the below link we will see there is a situation where we cant not use xapth generator tool directly because need to to use different function to handle the situation.

https://blogs.oracle.com/rajeshthekkadath/entry/xpath_searching_for_a_text


Please study xpath tutorial to learn what is xpath and how to build the xpath . I am providing few links which will give you a snapshot of the xpath.

i. http://www.w3schools.com/xsl/xpath_intro.asp
ii. http://www.tutorialspoint.com/xpath/
iii. https://www.seleniumeasy.com/selenium-tutorials/xpath-tutorial-for-selenium

How to use xpath in scrip


Sample code

WebDriver driver = new FirefoxDriver();

driver.findElement(By.xpath("//*[@id='BLUE_BAR_ID_DO_NOT_USE']/div/div/div[1]/div/div/ul/li[12]/a/span/span")).click();




How to install and configure cucumber -java

How to install Cucumber - java in eclipse

How to install cucumber java?

Prerequisite for installing Cucumber 


1. jdk (Latest jdk recomanded).
3.Eclipse plugins

   i. TestNG plugin - http://beust.com/eclipse
   ii. Cucumber eclipse plugin - http://cucumber.github.com/cucumber-eclipse/update-site

You need to download few cucumber related jars.

1. cucumber-core-1.2.5
2. cucumber-html-0.2.3
3. cucumber-java-1.2.5
4. cucumber-jvm-deps-1.0.5
5. cucumber-testng-1.2.5
6. gherkin-2.12.2
7. selenium-server-standalone-3.4.0
8. testng-6.11


To configure cucumber java you need to follow few steps

Step 1  :  Open eclipse and configure workspace 

how to install cucumber- java

Step 2  : Create a new project in eclipse  

You can create an new project from File > New >Java Project . You need to provide a name for that project , say "TestCucumber" and tap on Finish button. You will find "TestCucumber" is created in left side panel of eclipse IDE. 

how to install cucumber- java



Step 3 :  Configure java build path from eclipse .

You need to configure java build path . Means you need to add TestNG library and required external jars with this new project. 

a. Left click on the project. 



b.  Click on the Build Path > Configure Build Path ..




c.  Click on Add library and and TestNG and Click Next > Finish . TestNG will be added for this project.



d. Click on Add External JARs,, and navigate to downloaded location where there cucumber related jars are there. 

add external jars for cucumber

e.  Click on Open the Click on Ok button .. All required jars will be added with the project.

Step 4:  Create 3 package in side the TestCucumber/src 

a.  com.Cucumber.features :  This package consist all feature files. 
b  com.Cucumber.steps : Actual java program where selenium steps are written. 
c. com.Cucumber.Runners : This file consist configuration for the test. 

There I am creating a sample Cucumber project 

Sample feature file

Feature: Login Application
  As a user
  I want to login to the application

  Scenario: Valid user name and password
    Given I launch the url "http://www.fb.com"
    When I enter password and username
    And I click on login button
    Then I should see the Error message

You need to create a file under com.Cucumber.features package . File extension should be .feature
Cucumber feature file


Name of the sample feature file is demo.feature

Now you need to create actual selenium file under com.Cucumber.steps package.

Sample step java file 


package com.Cucumber.steps;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.testng.Assert;

import cucumber.api.java.en.Given;
import cucumber.api.java.en.Then;
import cucumber.api.java.en.When;

public class DemoLoginSteps {
 WebDriver driver;
 @Given("^I launch the url \"([^\"]*)\"$")
 public void i_launch_the_url(String arg1) throws Throwable {
     // Write code here that turns the phrase above into concrete actions
  System.setProperty("webdriver.chrome.driver", "C:\\Users\\anjan\\Desktop\\cucmber\\chromedriver\\chromedriver.exe");
  driver = new ChromeDriver();
  driver.get("http://www.fb.com");
     
 }

 @When("^I enter password and username$")
 public void i_enter_password_and_username() throws Throwable {
     // Write code here that turns the phrase above into concrete actions
  driver.findElement(By.name("email")).sendKeys("test");
  driver.findElement(By.name("pass")).sendKeys("cucumber");
  
 }

 @When("^I click on login button$")
 public void i_click_on_login_button() throws Throwable {
     // Write code here that turns the phrase above into concrete actions
 driver.findElement(By.xpath("//*[@data-testid='royal_login_button']")).click();
 }

 @Then("^I should see the login page$")
 public void i_should_see_the_Error_message() throws Throwable {
  try{
     // Write code here that turns the phrase above into concrete actions
   if(driver.findElement(By.name("email")).isDisplayed()){
    Assert.assertTrue(true);
   }else
    Assert.assertTrue(false);
  }catch(Exception NoSuchElementException){
    Assert.assertTrue(false);
  }finally{
   driver.quit();
  }
     
 }

}


Name of the step file is DemoLoginSteps

You can generate step code automatically, but you need to clear few lines of code like " throw new PendingException(); "from each methods and you need to write down the actual  selenium steps as per your requirements. Auto generated file is nothing but a skeleton of the methods.

How to generate step file automatically 

You just need to left click on the feature file and click on the Run As Cucumber feature . You will file unimplemented methods are displayed on eclipse console screen.
How to generate test step in cucumber
Create a RunTest Class under om.Cucumber.Runners package (You need to create om.Cucumber.Runners package under src folder)

Sample runner class


CucumberOptions(
     features = "src/com/Cucumber/features/Login.feature", 
     glue = "com.Cucumber.steps", 
     plugin = { "pretty", "html:target/cucumber-report" }, 
     monochrome = true)

public class RunTest extends AbstractTestNGCucumberTests {

}
Name of runner class is RunTest

How to write runner class using testng


feature  : Location of feature file in your project
glue : package name for the step java file
plugin : Reporting purpose
monochrome :This option can either set as true or false. If it is set as true, it means that the console output for the Cucumber test are much more readable. And if it is set as false, then the console output is not as readable as it should be. For practice just add the code ‘monochrome = true‘ in TestRunner class.

Create a testng file under project to run the RunTest file.

Testng XML

Cucumber with testng

You can run the test case without writing the xml file but testng xml will help you to create CI integration very easily.

How to run test case without testng xml 

 You need to run left click on the feature file and choose Run As Cucumber Feature.

How to run test case using testng xml

You just need to left click on the testng xml file and choose Run As TestNG suite.

How to use Datatable in cucumber


How to implement Datatable in cucumber

How to use Datatable in Cucumber


In my previous post How to install and configure cucumber -java  I have discussed how to install Cucumber and how to run cucumber program in java. In the previous post, I did not show how to parameterize the data. Means previously we passed parameters in the step line. Now we declared the variable in the feature file. So we are using Tables as arguments to Steps. 

I have created one feature file named: dataDriven.feature under com.Cucumber.features package.

how to user cucumber datatable

dataDriven.feature is almost same as the previous demo.feature . The only difference is the "when" .
previously it was " When I enter password and username" and now 

When I provide password and username
      | testname | [email protected] |




dataTable feature file 
 Feature: Login Application  
  As a user  
  I want to login to the application  
  Scenario: Valid user name and password  
   Given I launch the url "https://www.fb.com"  
   When I provide password and username  
    | testname | [email protected] |  
   And I click on login button  
   Then I should see the login page  

Now we need to write down the step file. As you see there are very few changes in scenario/feature file so we can re use all the methods except the step written under "@when"

The implementation of the @when step


 @When("^I provide password and username$")  
  public void i_enter_password_and_username(DataTable rawdata) throws Throwable {  
    // Write code here that turns the phrase above into concrete actions  
  List<List<String>> data = rawdata.raw();  
  driver.findElement(By.name("email")).sendKeys(data.get(0).get(0));  
  driver.findElement(By.name("pass")).sendKeys(data.get(0).get(1));   
  }   


The complete steps 

 package com.Cucumber.steps; import java.util.List;  
 import org.openqa.selenium.By;  
 import org.openqa.selenium.OutputType;  
 import org.openqa.selenium.TakesScreenshot;  
 import org.openqa.selenium.WebDriver;  
 import org.openqa.selenium.WebDriverException;  
 import org.openqa.selenium.chrome.ChromeDriver;  
 import org.testng.Assert;  
 import cucumber.api.DataTable;  
 import cucumber.api.Scenario;  
 import cucumber.api.java.After;  
 import cucumber.api.java.en.Given;  
 import cucumber.api.java.en.Then;  
 import cucumber.api.java.en.When;  
 public class DemoLoginSteps {  
  WebDriver driver;  
  @Given("^I launch the url \"([^\"]*)\"$")  
  public void i_launch_the_url(String arg1) throws Throwable {  
    // Write code here that turns the phrase above into concrete actions  
  System.setProperty("webdriver.chrome.driver", "C:\\Users\\anjan\\Desktop\\cucmber\\chromedriver\\chromedriver.exe");  
  driver = new ChromeDriver();  
  driver.get("http://www.fb.com");  
  }  
  @When("^I click on login button$")  
  public void i_click_on_login_button() throws Throwable {  
    // Write code here that turns the phrase above into concrete actions  
  driver.findElement(By.xpath("//*[@data-testid='royal_login_button']")).click();  
  }  
  @Then("^I should see the login page$")  
  public void i_should_see_the_Error_message() throws Throwable {  
  try{  
    // Write code here that turns the phrase above into concrete actions  
   if(driver.findElement(By.name("email")).isDisplayed()){  
   Assert.assertTrue(true);  
   }else  
   Assert.assertTrue(false);  
  }catch(Exception NoSuchElementException){  
   Assert.assertTrue(false);  
  }finally{  
   driver.quit();  
  }  
  }  
  @When("^I provide password and username$")  
  public void i_enter_password_and_username(DataTable rawdata) throws Throwable {  
    // Write code here that turns the phrase above into concrete actions  
  List<List<String>> data = rawdata.raw();  
  driver.findElement(By.name("email")).sendKeys(data.get(0).get(0));  
  driver.findElement(By.name("pass")).sendKeys(data.get(0).get(1));   
  }  
 }  




If you want to execute cucumber test from testng xml or just left click on feature file and Run As Cucumber Feature.



your ad