v5tech / notes

notes
https://ameizi.gitee.io/notes
MIT License
1.52k stars 378 forks source link

java截图 #168

Open v5tech opened 6 years ago

v5tech commented 6 years ago
<dependency>
    <groupId>org.apache.commons</groupId>
    <artifactId>commons-lang3</artifactId>
    <version>3.6</version>
</dependency>
<dependency>
    <groupId>com.google.guava</groupId>
    <artifactId>guava</artifactId>
    <version>23.0</version>
</dependency>
<dependency>
    <groupId>org.seleniumhq.selenium</groupId>
    <artifactId>selenium-java</artifactId>
    <version>3.6.0</version>
</dependency>
<dependency>
    <groupId>com.codeborne</groupId>
    <artifactId>phantomjsdriver</artifactId>
    <version>1.2.1</version>
</dependency>
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.phantomjs.PhantomJSDriver;

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

public class TakesScreenshotUtils {

    public static void main(String[] args) throws IOException {
        takesScreenshot1();
        takesScreenshot2();
    }

    public static void takesScreenshot1() throws IOException {
        System.setProperty("webdriver.chrome.driver", "D:\\chromedriver.exe");

        System.setProperty("phantomjs.binary.path", "D:\\phantomjs.exe");

        WebDriver driver = new PhantomJSDriver();

        driver.manage().window().maximize();

        driver.get("http://www.jianshu.com");

        //指定了OutputType.FILE做为参数传递给getScreenshotAs()方法,其含义是将截取的屏幕以文件形式返回。
        File srcFile = ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE);

        //利用FileUtils工具类的copyFile()方法保存getScreenshotAs()返回的文件对象。
        FileUtils.copyFile(srcFile, new File("screenshot.png"));

        //关闭浏览器
        driver.quit();
    }

    public static void takesScreenshot2() {
        Runtime rt = Runtime.getRuntime();
        Process process;
        try {
            process = rt.exec("D:\\phantomjs.exe" + " D:\\responsive-screenshot.js " + "http://www.baidu.com");
            try {
                process.waitFor();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}