如何使用 Selenium Webdriver 截取特定元素而非整个页面的屏幕截图?

seleniumautomation testingtesting tools更新于 2026/2/10 9:07:17

我们可以使用 Selenium Webdriver 截取特定元素而非整个页面的屏幕截图。项目中可能需要截取特定 Web 元素的屏幕截图。

首先,我们需要截取整个页面的屏幕截图,然后根据元素的尺寸和位置进行裁剪。我们将借助 TakeScreenShot 接口并使用其 getScreenshotAs 方法。

语法

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

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

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

示例

Code Implementation

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://www.tutorialspoint.com/index.htm");
      driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
      // 识别元素
      WebElement m=driver.findElement(By.xpath( "//*[@title='Tutorialspoint']"));
      // 完整页面截图
      File i = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
      BufferedImage fl = ImageIO.read(i);
      //web元素位置
      Point point= m.getLocation();
      // web元素维度
      int wd= m.getSize().getWidth();
      int ht=m.getSize().getHeight();
      // 将图片裁剪到元素大小
      BufferedImage c= fl.getSubimage(point.getX(), point.getY(), wd, ht);
      ImageIO.write(c, "png", i);
      //将截图复制到项目文件夹内的文件中
      FileUtils.copyFile(i, new File("logo.png"));
      driver.close();
   }
}

相关文章