java网页如何截图
使用 Selenium 进行网页截图
Selenium 是一个自动化测试工具,也可以用于网页截图。需要安装 Selenium WebDriver 和对应的浏览器驱动(如 ChromeDriver)。
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.OutputType;
import org.apache.commons.io.FileUtils;
import java.io.File;
public class ScreenshotExample {
public static void main(String[] args) {
System.setProperty("webdriver.chrome.driver", "path/to/chromedriver");
WebDriver driver = new ChromeDriver();
driver.get("https://example.com");
File screenshot = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
FileUtils.copyFile(screenshot, new File("screenshot.png"));
driver.quit();
}
}
使用 AShot 进行截图
AShot 是一个专门用于网页截图的库,可以处理全页截图和特定元素的截图。
import ru.yandex.qatools.ashot.AShot;
import ru.yandex.qatools.ashot.Screenshot;
import javax.imageio.ImageIO;
import java.io.File;
public class AShotExample {
public static void main(String[] args) {
WebDriver driver = new ChromeDriver();
driver.get("https://example.com");
Screenshot screenshot = new AShot().takeScreenshot(driver);
ImageIO.write(screenshot.getImage(), "PNG", new File("fullpage.png"));
driver.quit();
}
}
使用 Java 原生方法
对于简单的截图需求,可以使用 Java 原生的 Robot 类来捕获屏幕。
import java.awt.Robot;
import java.awt.Rectangle;
import java.awt.Toolkit;
import java.awt.image.BufferedImage;
import javax.imageio.ImageIO;
import java.io.File;
public class RobotExample {
public static void main(String[] args) {
BufferedImage screenshot = new Robot().createScreenCapture(
new Rectangle(Toolkit.getDefaultToolkit().getScreenSize())
);
ImageIO.write(screenshot, "PNG", new File("screenshot.png"));
}
}
使用第三方 API
某些第三方服务(如 Browshot、Urlbox)提供网页截图 API,可以通过 HTTP 请求获取截图。

import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.net.URL;
public class ApiExample {
public static void main(String[] args) {
String apiUrl = "https://api.browshot.com/v1/screenshot?url=https://example.com&key=YOUR_API_KEY";
try (InputStream in = new URL(apiUrl).openStream()) {
Files.copy(in, Paths.get("api_screenshot.png"));
}
}
}
注意事项
- Selenium 和 AShot 需要配置浏览器驱动,确保与浏览器版本兼容。
Robot类只能捕获当前屏幕内容,不适合捕获完整网页。- 第三方 API 可能需要付费或限制调用次数。
- 截图时注意网页加载延迟,可以添加等待时间确保页面完全加载。






