Highlight Element using Selenium WebDriver
During automation testing, it is always useful to know which steps are being performed in browser. This is especially helpful in debugging your test script. One way to know steps being performed in browser is to highlight the web page elements. This post focuses on that very purpose. It explains how we can highlight element using Selenium WebDriver.
There was a way for doing this in earlier Selenium version. Highlights API command ‘selenium.highlight’ could be used to highlight elements of web page in Selenium 1.0. However, there is no such native API available out of the box for Selenium WebDriver. But, we can achieve this using the JavaScript Executor.
We will explain this with a simple example. Our example will open Google home page and highlight a search box. Follow below steps to implement this.
- Write below JavaScript Executor code in your Class file.
1234567891011public void elementHighlight(WebElement element) {for (int i = 0; i < 2; i++) {JavascriptExecutor js = (JavascriptExecutor) driver;js.executeScript("arguments[0].setAttribute('style', arguments[1]);",element, "color: red; border: 3px solid red;");js.executeScript("arguments[0].setAttribute('style', arguments[1]);",element, "");}} - Call the above method from Selenium test case to highlight a web page element. Check out below code which shows how it is done. elementHighlight method is called with searchBox as an argument.
1234567891011@Testpublic void GoogleSearch() throws Exception, SQLException {driver.findElement(By.xpath("//center/div[2]")).click();WebElement searchBox = driver.findElement(By.xpath("//div[3]/div/input"));elementHighlight(searchBox);driver.findElement(By.xpath("//div[3]/div/input")).clear();driver.findElement(By.xpath("//div[3]/div/input")).sendKeys("Test");driver.findElement(By.xpath("//button")).click();} - On executing the above test, Selenium test will highlight the search box on Google home page. You can reuse elementHighlight method for highlighting any elements on web page.
Try out the above example to highlight element using Selenium WebDriver. This may come in handy to you for debugging your Selenium script. Be wary though. Excessive use of this method may slow down your Selenium execution. This is because JavaScript Executor is used here.
Also, you can experiment by modifying style of highlighting box in the above method. Try it out yourself and let us know if you found this tip helpful.
I tried this code and i could not see anything…
Is it possible the reason for this is that i pulled the assignment to the js variable outside of the ‘for’ loop? I did not understand why the driver needs to be assigned twice (or, does it?)
Thanks
Does this solution support highlight of Mobile Native Elements in App? If not, do you have any other other solution which can achieve that?