如何使用 Selenium Webdriver 捕获特定元素的屏幕截图,而不是整个页面?


我们可以使用 Selenium webdriver 捕获特定元素的屏幕截图,而不是整个页面。项目中可能有一些需求,我们需要捕获特定 Web 元素的屏幕截图。

首先,我们将捕获整个页面的屏幕截图,然后根据元素的维度和位置进行裁剪。我们将借助 TakeScreenShot 接口及其 getScreenshotAs 方法。

语法

File i = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);

接下来,将图片存储在文件中 [例如,.jpeg、.png]。

FileUtils.copyFile(i, new File("<<path of file>>"))

示例

代码实现

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import java.util.concurrent.TimeUnit;
import java.io.File;
import org.apache.commons.io.FileUtils;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.Point;
import java.awt.image.BufferedImage;
public class ElementScreenshot{
   public static void main(String[] args) {
      System.setProperty("webdriver.chrome.driver", "C:\Users\ghs6kor\Desktop\Java\chromedriver.exe");
      WebDriver driver = new ChromeDriver();
      driver.get("https://tutorialspoint.com/index.htm");
      driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
      // identify element
      WebElement m=driver.findElement(By.xpath( "//*[@title='Tutorialspoint']"));
      // full page screenshot capture
      File i = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
      BufferedImage fl = ImageIO.read(i);
      //webelement location
      Point point= m.getLocation();
      // webelement dimension
      int wd= m.getSize().getWidth();
      int ht=m.getSize().getHeight();
      // Crop Image to the element
      BufferedImage c= fl.getSubimage(point.getX(), point.getY(), wd, ht);
      ImageIO.write(c, "png", i);
      //copy screenshot to a file inside project folder
      FileUtils.copyFile(i, new File("logo.png"));
      driver.close();
   }
}

更新于:2020-10-26

2K+ 浏览量

开启你的 职业生涯

完成课程即可获得认证

开始
广告
© . All rights reserved.