使用firefox浏览器无头模式在内存里渲染页面,然后用selenium操作浏览器并解析截图。需要安装firefox(也支持chrome),然后下载firefox 驱动 详见:https://github.com/mozilla/geckodriver/releases。下载完成后存放任意路径,然后将代码中的geckoDriver 改为驱动的实际路径即可。
import org.openqa.selenium.*;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.firefox.FirefoxOptions;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
import sun.misc.BASE64Decoder;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.concurrent.TimeUnit;
/**
* 网页截图
*/
public class WebPageScreenShot {
/**
* fireFox驱动路径
*/
String geckoDriver = "C:\\Program Files\\Python37\\geckodriver.exe";
String type="png";
public void loadPage(String logonUrl,String actionUrl,String resultPath) throws IOException, InterruptedException {
System.setProperty("webdriver.gecko.driver", geckoDriver);//chromedriver服务地址
FirefoxOptions firefoxOptions = new FirefoxOptions();
firefoxOptions.addArguments("-headless");
//firefoxOptions.addArguments("--start-maximized");
//firefoxOptions.addArguments("--start-fullscreen");
firefoxOptions.setHeadless(true);
FirefoxDriver driver = new FirefoxDriver(firefoxOptions); //新建一个WebDriver 的对象,但是new 的是FirefoxDriv