Protected by Copyscape
Powered By Blogger

Sunday, January 12, 2020

How to highlight web elements using Selenium?

To highlight web element in automation testing is a good way to track the execution flow which is being processed. But to perform the same using Selenium Webdriver is not possible at all as no inbuilt method provided by WebDriver to perform such operations like other tools provide i.e. QTP.

To make this happen with Selenium we need to use Java Script code and to execute that code with Selenium Web Driver we will use JavascriptExecutor, which is an Interface in java.

The below code java script needs to be executed with JavascriptExecutor.

"arguments[0].setAttribute('style','background:cyan;border:solid green;');"

Syntax:
JavascriptExecutor js =(JavascriptExecutor)driver;
js.executeScript(script,arguments);

Here, I am taking an example of google.co.in where i want to highlight Search text box.

import java.util.concurrent.TimeUnit;
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 Highlight
{
public static WebDriver driver;
public static JavascriptExecutor js;



public static void main(String args[])
{
System.setProperty("webdriver.chrome.driver", "E:\\Selenium\\chromedriver.exe");
driver=new ChromeDriver();
driver.manage().window().maximize();
driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);

driver.get("http://www.google.co.in");
WebElement txtSearch=driver.findElement(By.name("q"));
HighLight(txtSearch);
}

public static void HighLight(WebElement element)
{
js=(JavascriptExecutor)driver;
js.executeScript("arguments[0].setAttribute('style','background:cyan;border:solid green;');", element);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
js.executeScript("arguments[0].setAttribute('style','background:cyan;border:solid red;');", element);
}

}


Output:


No comments: