Friday, September 13, 2019

Post#37.Capturing Screenshot in Selenium Part-3 (Highlight the Element in screenshot)

Highlight the Element in screenshot using Selenium webdriver

Scenario: I want to take a screenshot of my web page and I want to highlight the element, how to do it?
Solution:

  • Donot exactly do what asked in the question, but understand the scenario.
  • They expect a screenshot with element highlighted
  • First, highlight the element instead of taking screenshot.
  • Once the element is been highlighted take the screenshot.
Complete program to take screenshot with highlighted element.
public class HighLightElementInScreenshot {
              public static void main(String[] args) throws Exception {
                             // set the geckodriver.exe property
                             System.setProperty("webdriver.gecko.driver", "C:/PATH/geckodriver.exe");
                             WebDriver driver =new FirefoxDriver();
                             driver.manage().window().maximize();

                             // set time limit to find the element
                             driver.manage().timeouts().implicitlyWait(60, TimeUnit.SECONDS);

                             // Go to URL
                             driver.get("http://newtours.demoaut.com/");
                             // store the webelement
                             WebElement element_node = driver.findElement(By.xpath("//input"));
                             // pass the stored webelement to javascript executor
    JavascriptExecutor jse = (JavascriptExecutor) driver;
    // highlight the element with red border 3px width
    jse.executeScript("arguments[0].style.border='3px solid red'", element_node);
    // added sleep to give little time for browser to respond
    Thread.sleep(3000);

                             // Take the ScreenShot
                             File file = ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE);

                             // store the converted file as Image on D driver
                             FileUtils.copyFile(file, new File("D:\\Element With Highlight.png"), true);
  }
}

No comments:

Post a Comment