java如何截图网页
使用Selenium截取网页截图
Selenium是一个自动化测试工具,可以用于控制浏览器并截取网页截图。需要安装Selenium WebDriver和对应的浏览器驱动。
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 Screenshot {
public static void main(String[] args) throws Exception {
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();
}
}
使用HtmlUnit截取网页截图
HtmlUnit是一个无界面浏览器,可以用于网页截图,但需要配合其他库如Flying Saucer。
import com.gargoylesoftware.htmlunit.WebClient;
import com.gargoylesoftware.htmlunit.html.HtmlPage;
import org.xhtmlrenderer.swing.Java2DRenderer;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
public class HtmlUnitScreenshot {
public static void main(String[] args) throws Exception {
WebClient webClient = new WebClient();
HtmlPage page = webClient.getPage("https://example.com");
BufferedImage image = new Java2DRenderer(page, 1024, 768).getImage();
ImageIO.write(image, "png", new File("screenshot.png"));
webClient.close();
}
}
使用第三方API截取网页截图
一些第三方服务提供网页截图API,可以通过HTTP请求获取截图。
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
public class ApiScreenshot {
public static void main(String[] args) throws Exception {
String apiUrl = "https://www.screenshotapi.io/api?url=https://example.com";
URLConnection connection = new URL(apiUrl).openConnection();
InputStream inputStream = connection.getInputStream();
FileOutputStream outputStream = new FileOutputStream("screenshot.png");
byte[] buffer = new byte[2048];
int length;
while ((length = inputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, length);
}
outputStream.close();
inputStream.close();
}
}
注意事项
Selenium方法需要安装浏览器驱动,适合需要真实浏览器渲染的情况。HtmlUnit方法不需要浏览器,但可能无法完全模拟现代浏览器。第三方API方法最简单,但可能有使用限制或需要付费。

所有方法都需要处理异常,确保资源正确关闭。截图质量取决于网页复杂度和渲染方式,可能需要调整参数获得最佳效果。






