Problem Statement:
How to highlight an element in Selenium Webdriver?
Solution : We can
highlight an element in Selenium WebDriver by creating a custom method to
highlight an element using JavaScriptexecutor.
What is
JavaScriptexecutor?
JavaScriptexecutor
class provides mechanism to execute Javascript through selenium driver. JavaScript executor provides two
methods to execute javascript in the code:
a.) executeAsyncScript - Execute an
asynchronous code of JavaScript
b.) executeScript - Executes a code of JavaScript.
Parameters
for the two methods are the Script to be executed and arguments for the script.
Below package needs to be imported to use
JavascriptExecutor:
import
org.openqa.selenium.JavascriptExecutor;
Below code explains how to use JavaScriptExecutor to highlight an element in Selenium WebDriver using Java.
import java.io.File;
import org.openqa.selenium.By;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.ie.InternetExplorerDriver;
public class testingC {
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("D:\\selenium\\IEDriverServer.exe");
System.setProperty("webdriver.ie.driver", file.getAbsolutePath());
try{
driver = new InternetExplorerDriver();
//added new line to maximise browser on launch
driver.manage().window().maximize();
}
catch(Exception e)
{
driver=new InternetExplorerDriver();
}
//Navigate to the webpage and identify the element to be highigted
driver.navigate().to("https://qaautomationqtp.blogspot.com");
WebElement element = driver.findElement(By.linkText("Play"));
//highlight the element
methodhighlightElement(element);
element.click();
}
public static void methodhighlightElement(WebElement element) throws InterruptedException
{
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, "");
}
}
No comments:
Post a Comment