在Java中通过无头浏览器创建网络截图

时间:2019-05-07 11:59:07

标签: java headless-browser

我需要实现一个为Java后端项目中的网页制作屏幕截图的功能。我发现一些方法,例如使用无头浏览器是一种好方法,但是对于长页面或包含太多图像,它们都无法完美地表现出来(例如jbrowser和ashot)。我发现firefox具有可以为我制作屏幕截图的功能。我想知道在无头模式下是否有用于此功能的Java API?还是有其他方法可以获得更好的屏幕截图性能?非常感谢

这是获取屏幕截图的代码

package screenshot;

import com.machinepublishers.jbrowserdriver.JBrowserDriver;
import com.machinepublishers.jbrowserdriver.Settings;
import com.machinepublishers.jbrowserdriver.Timezone;
import org.openqa.selenium.Dimension;
import org.openqa.selenium.OutputType;
import ru.yandex.qatools.ashot.AShot;
import ru.yandex.qatools.ashot.Screenshot;
import ru.yandex.qatools.ashot.shooting.ShootingStrategies;


import javax.imageio.ImageIO;
import java.io.*;


public class JbrowserTest {


    public String chekUrl(String str){
        if (str.startsWith("http://") || str.startsWith("https://")) {
            return str;
        }
return str;

    }
    public static void main(String[] args) throws UnsupportedEncodingException {

        // You can optionally pass a Settings object here,
        // constructed using Settings.Builder
        JBrowserDriver driver = new JBrowserDriver(Settings.builder().
                timezone(Timezone.ASIA_SHANGHAI).screen(new Dimension(1920,1080)).build());
        String url3 = "http://www.google.com";
        // This will block for the page load and any
        // associated AJAX requests
        driver.get(url3);
        driver.manage().window().maximize();
        // You can get status code unlike other Selenium drivers.
        // It blocks for AJAX requests and page loads after clicks
        // and keyboard events.
        System.out.println(driver.getStatusCode());
        // Returns the page source in its current state, including
        // any DOM updates that occurred after page load
        String string2 = new String(driver.getPageSource().getBytes("utf-8"),"gb2312");
        System.out.println(string2);
        Screenshot screenshot2 = new AShot().shootingStrategy(ShootingStrategies.viewportPasting(100))
                .takeScreenshot(driver);
        try {
            ImageIO.write(screenshot2.getImage(), "PNG",
                    new File("/Users/*******/Desktop/test2.png"));
            byte[] screenshot = driver.getScreenshotAs(OutputType.BYTES);
            System.out.println("the bytes" + screenshot.length);
            String filePath = "/Users/*******/Desktop/test.png";
            File file = new File(filePath);
            FileOutputStream fw = new FileOutputStream(file);
            fw.write(screenshot);
            fw.close();
        } catch (Exception ex) {
            System.out.println("error" + ex);
        }
        // Close the browser. Allows this thread to terminate.
        driver.quit();
    }
}

1 个答案:

答案 0 :(得分:0)

您没有完全指定“性能要求”。利用硒和铬驱动程序获取屏幕截图的简单方法:

private void loadWebpage(){        
//Init driver
    ChromeOptions options = new ChromeOptions();
    options.setHeadless(true);

    options.addArguments("--window-size=1200x600", "--log-level=3");

    WebDriver driver = new ChromeDriver(options);

    //Load your website & wait until loaded with webdriver wait
     takeScreenShot(driver, new File("outputFile.png"))
}

public static void takeScreenshot(WebDriver driver, File screenshotFile) throws 
IOException {
    File scrFile = ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE);
    Files.copy(scrFile.toPath(), screenshotFile.toPath(), StandardCopyOption.REPLACE_EXISTING);
}