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 do scroll action till the particular element is present in appium


How to do scroll action till the particular element is present in appium ?


How to do scroll action till the particular element is present or not
I am currently working on appium for automating WhatsApp mobile application. I needed one method which would perform the ‘scroll’ action to a particular name or number and choose to click on a particular name or number. So I googled for that method and I found out that there are two methods, scrollTo(), scrollToExact(), which was supposed to solve my problem. But when  I started writing the code and again I faced another problem.  I am using appium java client 5.0.0-BETA9 (updated version )and on this version, there are no such methods like scrollTo() or scrollToExact().  Previously I had worked on the seetest tool and it is a mobile automation tool, there was a method called ‘swipewhileNotFound’ which would scroll the app view until the desired object was visible.  SeeTest is a licensed tool. Hence there are several readymade methods available for automating mobile application.  So I started writing this method for appium because I needed this method for appium to work.


I have used TestNG to write the test, but you can use any testing framework or simple Java class with the method mentioned above. I have posted my code here so that you can have a look at it. Also, you can download the complete java file from the below link


How to do scroll action till the particular element is present or not

 package appium;  
 import java.net.MalformedURLException;  
 import java.net.URL;  
 import java.util.concurrent.TimeUnit;  
 import org.openqa.selenium.By;  
 import org.openqa.selenium.Dimension;  
 import org.openqa.selenium.WebElement;  
 import org.openqa.selenium.remote.DesiredCapabilities;  
 import org.testng.annotations.*;  
 import io.appium.java_client.android.AndroidDriver;  
 public class WhatsAppAutomate {  
 // WebDriver driver;  
 protected AndroidDriver driver;  
 @BeforeClass  
  public void setUp() throws MalformedURLException {  
  DesiredCapabilities capabilities = new DesiredCapabilities();  
  capabilities.setCapability("deviceName", "8fe5de4a");  
  capabilities.setCapability("platformName", "Android");  
  capabilities.setCapability("appPackage", "com.whatsapp");  
  // This package name of your app (you can get it from apk info app)  
  capabilities.setCapability("appActivity", "com.whatsapp.Main");   
  driver = new AndroidDriver(new URL("http://192.168.0.102:5036/wd/hub"), capabilities);  
 }  
  @Test  
  public void testCal() throws Exception {  
  swipeWhileNotFound("down","//*[@text='Anjan Mondal']",1000,3000,3000,17,true);  
  }  
  public void swipeWhileNotFound(String direction, String xpath,int offset,int waitTime,int duration,int round, boolean click) throws InterruptedException {  
   Dimension size = driver.manage().window().getSize();  
  int startx = size.width/2;  
  int starty=0;  
  int endy=0;  
  try {  
  driver.manage().timeouts().implicitlyWait(1, TimeUnit.SECONDS);  
  boolean loop = true;  
  int count = 0;  
  while (loop) {  
  if (count == round) {  
  System.out.println("round over");  
  break;  
  }  
  if (driver.findElements(By.xpath(xpath)).size() > 0) {  
  loop = false;  
  System.out.println("element found");  
  WebElement elm = driver.findElement(By.xpath(xpath));  
  if (click)  
  elm.click();  
  } else {  
  if(direction.toUpperCase().equals("UP")){   
  starty=size.height-offset;  
  endy = (int) (size.height * 0.60);  
  driver.swipe(startx, starty, startx, endy, duration);  
  Thread.sleep(waitTime);  
  }else if(direction.toUpperCase().equals("DOWN")){  
  starty = (int) (size.height * 0.80);   
  endy= offset;  
  driver.swipe(startx, endy, startx, starty, duration);  
  Thread.sleep(waitTime);  
  }   
  count++;  
  }  
  }  
  } catch (Exception e) {  
  System.out.print(e);  
  } finally {  
  driver.manage().timeouts().implicitlyWait(15, TimeUnit.SECONDS);  
  }  
  }  
  @AfterClass  
  public void teardown() {  
  // close the app  
  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 



your ad