java - 用 Java 截取网页的屏幕截图

标签 java screenshot

有没有免费的工具可以读取给定的网页并截图?

最佳答案

Selenium Webdriver 使用 VirtualFramebuffer 和 Firefox Binary 获得了最好的结果。 这是在ubuntu下测试的。你需要安装 xvfb 和 firefox

首先安装firefox和虚拟帧缓冲:

aptitude install xvfb firefox

编译运行这个类,之后打开/tmp/screenshot.png

import java.io.File;
import java.io.IOException;

import org.apache.commons.io.FileUtils;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxBinary;
import org.openqa.selenium.firefox.FirefoxDriver;

public class CaptureScreenshotTest
{
    private static int      DISPLAY_NUMBER  = 99;
    private static String   XVFB            = "/usr/bin/Xvfb";
    private static String   XVFB_COMMAND    = XVFB + " :" + DISPLAY_NUMBER;
    private static String   URL             = "http://www.google.com/";
    private static String   RESULT_FILENAME = "/tmp/screenshot.png";

    public static void main ( String[] args ) throws IOException
    {
        Process p = Runtime.getRuntime().exec(XVFB_COMMAND);
        FirefoxBinary firefox = new FirefoxBinary();
        firefox.setEnvironmentProperty("DISPLAY", ":" + DISPLAY_NUMBER);
        WebDriver driver = new FirefoxDriver(firefox, null);
        driver.get(URL);
        File scrFile = ( (TakesScreenshot) driver ).getScreenshotAs(OutputType.FILE);
        FileUtils.copyFile(scrFile, new File(RESULT_FILENAME));
        driver.close();
        p.destroy();
    }
}

关于java - 用 Java 截取网页的屏幕截图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1504034/

相关文章:

java - 展开文件名,重新插入到属性对象中

java - 编写全局监听器

java - Flink RichMapFunction 中未调用 open 方法

java - 找不到处理 Intent android.intent.action.REQUEST_TANGO_PERMISSION 的 Activity (有额外功能)

browser - 有什么方法可以使用 javascript 将浏览器网页中特定 div 标签的内容(比如图形)保存为图像?

android - 使用相机预览截取 SurfaceView 的屏幕截图

java - 无法创建新的 PoolingHttpClientConnectionManager

Linux:启动窗口、捕获屏幕

android - 我的 android 应用程序中有两个 Activity 。在我的第二个 Activity 中,我有一个按钮可以截取之前 Activity 的屏幕截图

screenshot - 与屏幕截图相关的 Itunes Connect 问题