网页快照实现-Java探险之旅

金融科
• 阅读 4040

引言

在监控系统、网页爬虫、审核流程等领域,经常需要保存系统在某一时刻的状态-网页快照。实现网页快照主要有phantomjs、selenium,但是网上资料都是零碎的,本文主要采用Selenium,详细阐述从编码到部署的整个流程.

一、添加Selenium依赖

<dependency>
    <groupId>org.seleniumhq.selenium</groupId>
    <artifactId>selenium-java</artifactId>
    <version>3.11.0</version>
</dependency>

二、实现网页快照

(1) 创建WebDriver

a.手机设备

public WebDriver createWebDriver(String device) {
    Map<String, String> mobileEmulation = new HashMap<String, String>();
    //设置设备,例如:Google Nexus 7/Apple iPhone 6
    //mobileEmulation.put("deviceName", "Google Nexus 7");
    if(StringUtils.isBlank(device))
        device = "iPhone 6";
    mobileEmulation.put("deviceName", device);   //这里是要使用的模拟器名称,就是浏览器中模拟器中的顶部型号
    Map<String, Object> chromeOptions = new HashMap<String, Object>();
    chromeOptions.put("mobileEmulation", mobileEmulation);
    DesiredCapabilities capabilities = DesiredCapabilities.chrome();
    capabilities.setCapability(ChromeOptions.CAPABILITY, chromeOptions);
    WebDriver driver = new ChromeDriver(capabilities);
    Dimension dimension = new Dimension(420, 900);
    driver.manage().window().setSize(dimension);
    return driver;
}

b.PC设备

public WebDriver createWebDriver(String device) {
    //暂时采用特定分辨率
    ChromeOptions options = new ChromeOptions();
    options.addArguments("window-size=1200,800");
    WebDriver driver = new ChromeDriver(options);
    driver.manage().window();
    return driver;
}

(2) 绘制图像

    public String execute(String uri, String device) {
        PerfCounter.count("miui_ad_schedule_capture.execute.total", 1L);
        long start = System.currentTimeMillis();
        System.setProperty("webdriver.chrome.driver", "/home/rd/chromedriver");
        //windows: System.setProperty("webdriver.chrome.driver", "src/main/resources/driver/chromedriver.exe");
        WebDriver driver = createWebDriver(device);
        String cdnUrl = "";
        try {
            driver.get(uri);
            cdnUrl = savePage(driver, url, "capture_" + System.currentTimeMillis() + ".png");
        } catch (Exception e) {
            logger.error("capture fail: [{},{}],{} !", uri ,device,e);
            throw new RuntimeException(String.format("save page failed, uri=%s, device=%s"));
        } finally {
            driver.close();
            driver.quit();
        }
        PerfCounter.count("miui_ad_schedule_capture.execute.success", 1L, System.currentTimeMillis() - start);
        return cdnUrl;
    }

    private String savePage(WebDriver driver, String filePath, String fileName) throws IOException, InterruptedException, NoSuchAlgorithmException {
        JavascriptExecutor jsExecutor = (JavascriptExecutor) driver;
        TakesScreenshot takesScreenshot = (TakesScreenshot) driver;
        jsExecutor.executeScript("window.scrollTo(0,0)");
        BufferedImage imageOriginal = new BufferedImage(1, 1, BufferedImage.TYPE_INT_RGB);// 创建全屏截图
        int lastScroll = -1;
        int currentScroll = 0;
        Thread.sleep(1000);
        while (lastScroll != currentScroll) {
            byte[] bytesScroll = takesScreenshot.getScreenshotAs(OutputType.BYTES);
            BufferedImage imageScroll = ImageIO.read(new ByteArrayInputStream(bytesScroll));
            int screenHeight = imageScroll.getHeight();
            int screenWidth = imageScroll.getWidth();

            BufferedImage combined = new BufferedImage(screenWidth, currentScroll + screenHeight, BufferedImage.TYPE_INT_RGB);
            Graphics g = combined.getGraphics();
            g.drawImage(imageOriginal, 0, 0, null);
            g.drawImage(imageScroll, 0, currentScroll, null);
            imageOriginal = combined;

            logger.info("lastScroll:" + lastScroll + "    currentScroll:" + currentScroll + "    screenHeight:" + screenHeight);
            int scrollTo = currentScroll + screenHeight;
            lastScroll = currentScroll;
            jsExecutor.executeScript("window.scrollTo(0," + scrollTo + ")");
            currentScroll = Double.valueOf(jsExecutor.executeScript("return document.documentElement.scrollTop").toString()).intValue();
            if (lastScroll > 5000) {
                break;
            }
            //网络加载
            Thread.sleep(1000);
        }

        File path = new File(filePath);
        if (!path.exists() || !path.isDirectory()) {
            path.mkdirs();
        }
        File file = new File(path.getAbsolutePath() + File.separatorChar + fileName);
        ImageIO.write(imageOriginal, "png", file);
        String uploadPath = FileStorageUtils.upload(file.getAbsolutePath(), CHANNEL_ID);
        if(file.exists()){
            file.delete();
        }
        return uploadPath;
    }

三、部署(ubantu16.04)

(1) 安装chrome

sudo apt-get install libxss1 libappindicator1 libindicator7 #install dependency
wget https://dl.google.com/linux/direct/google-chrome-stable_current_amd64.deb
sudo dpkg -i google-chrome*.deb  
sudo apt-get install -f

安装完成后测试:

google-chrome --headless --remote-debugging-port=9222 https://chromium.org --disable-gpu

这里是使用headless模式进行远程调试,ubuntu上大多没有gpu,所以--disable-gpu以免报错。之后使用另一个命令行访问本地的9222端口:

curl http://localhost:9222

能够看到调试信息应该就是安装成功了

(2) 下载chromedriver

chromedriver提供了操作chrome的api,是selenium控制chrome的桥梁。
可以到:https://sites.google.com/a/ch...
下载并解压:

wget https://chromedriver.storage.googleapis.com/2.37/chromedriver_linux64.zip
unzip chromedriver_linux64.zip

Chrome与WebDriver的版本对应关系:

chromedriver版本 支持的Chrome版本
v2.37 v64-66
v2.36 v63-65
v2.35 v62-64
v2.34 v61-63
v2.33 v60-62
v2.32 v59-61
v2.31 v58-60
v2.30 v58-60
v2.29 v56-58
v2.28 v55-57
v2.27 v54-56
v2.26 v53-55
v2.25 v53-55
v2.24 v52-54
v2.23 v51-53
v2.22 v49-52
v2.21 v46-50
v2.20 v43-48
v2.19 v43-47
v2.18 v43-46
v2.17 v42-43
v2.13 v42-45
v2.15 v40-43
v2.14 v39-42
v2.13 v38-41
v2.12 v36-40
v2.11 v36-40
v2.10 v33-36
v2.9 v31-34
v2.8 v30-33
v2.7 v30-33
v2.6 v29-32
v2.5 v29-32
v2.4 v29-32

(3) 安装Xfvb

如果不安装Xfvb,java -jar xxx.jar 将报一下错误:

Starting ChromeDriver 2.30.477691 (6ee44a7247c639c0703f291d320bdf05c1531b57) on port 14103
Only local connections are allowed.
Exception in thread "main" org.openqa.selenium.WebDriverException: unknown error: Chrome failed to start: exited abnormally
  (Driver info: chromedriver=2.30.477691 (6ee44a7247c639c0703f291d320bdf05c1531b57),platform=Linux 4.9.15-x86_64-linode81 x86_64) (WARNING: The server did not provide any stacktrace information)
Command duration or timeout: 60.13 seconds
Build info: version: 'unknown', revision: 'unknown', time: 'unknown'
System info: host: 'localhost', ip: '127.0.0.1', os.name: 'Linux', os.arch: 'amd64', os.version: '4.9.15-x86_64-linode81', java.version: '1.8.0_131'
Driver info: driver.version: ChromeDriver
    at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
    ...

安装方式:
a.安装Xvfb

sudo apt install Xvfb

b.启动Xvfb服务

Xvfb -ac :7 -screen 0 1280x1024x8 &

c.连接服务7

export DISPLAY=:7
关于Xvfb的具体应用请参考:https://www.x.org/archive/X11R7.6/doc/man/man1/Xvfb.1.xhtml

参考链接:
https://blog.csdn.net/codebat...
https://jiayi.space/post/zai-...

博客编写不易,如果觉得写得可以,请帮忙点个赞

点赞
收藏
评论区
推荐文章
blmius blmius
4年前
MySQL:[Err] 1292 - Incorrect datetime value: ‘0000-00-00 00:00:00‘ for column ‘CREATE_TIME‘ at row 1
文章目录问题用navicat导入数据时,报错:原因这是因为当前的MySQL不支持datetime为0的情况。解决修改sql\mode:sql\mode:SQLMode定义了MySQL应支持的SQL语法、数据校验等,这样可以更容易地在不同的环境中使用MySQL。全局s
Oracle 分组与拼接字符串同时使用
SELECTT.,ROWNUMIDFROM(SELECTT.EMPLID,T.NAME,T.BU,T.REALDEPART,T.FORMATDATE,SUM(T.S0)S0,MAX(UPDATETIME)CREATETIME,LISTAGG(TOCHAR(
Wesley13 Wesley13
4年前
MySQL部分从库上面因为大量的临时表tmp_table造成慢查询
背景描述Time:20190124T00:08:14.70572408:00User@Host:@Id:Schema:sentrymetaLast_errno:0Killed:0Query_time:0.315758Lock_
皕杰报表之UUID
​在我们用皕杰报表工具设计填报报表时,如何在新增行里自动增加id呢?能新增整数排序id吗?目前可以在新增行里自动增加id,但只能用uuid函数增加UUID编码,不能新增整数排序id。uuid函数说明:获取一个UUID,可以在填报表中用来创建数据ID语法:uuid()或uuid(sep)参数说明:sep布尔值,生成的uuid中是否包含分隔符'',缺省为
Jacquelyn38 Jacquelyn38
4年前
2020年前端实用代码段,为你的工作保驾护航
有空的时候,自己总结了几个代码段,在开发中也经常使用,谢谢。1、使用解构获取json数据let jsonData  id: 1,status: "OK",data: 'a', 'b';let  id, status, data: number   jsonData;console.log(id, status, number )
Stella981 Stella981
4年前
Python+Selenium自动化篇
本篇文字主要学习selenium定位页面元素的集中方法,以百度首页为例子。0.元素定位方法主要有:id定位:find\_element\_by\_id('')name定位:find\_element\_by\_name('')class定位:find\_element\_by\_class\_name(''
Easter79 Easter79
4年前
Twitter的分布式自增ID算法snowflake (Java版)
概述分布式系统中,有一些需要使用全局唯一ID的场景,这种时候为了防止ID冲突可以使用36位的UUID,但是UUID有一些缺点,首先他相对比较长,另外UUID一般是无序的。有些时候我们希望能使用一种简单一些的ID,并且希望ID能够按照时间有序生成。而twitter的snowflake解决了这种需求,最初Twitter把存储系统从MySQL迁移
Wesley13 Wesley13
4年前
mysql设置时区
mysql设置时区mysql\_query("SETtime\_zone'8:00'")ordie('时区设置失败,请联系管理员!');中国在东8区所以加8方法二:selectcount(user\_id)asdevice,CONVERT\_TZ(FROM\_UNIXTIME(reg\_time),'08:00','0
Stella981 Stella981
4年前
Selenium使用及原理
1、Selenium介绍Selenium是一个Web测试工具,通过直接控制浏览器来实现Web测试,与真实用户操作完全一致。Selenium目前支持IE、Firefox、Chrome、Safari、Opera等浏览器,Selenium支持主流的操作系统平台Windows、Linux、Mac等,Selenium支持Java、Ruby、Python
Stella981 Stella981
4年前
Django中Admin中的一些参数配置
设置在列表中显示的字段,id为django模型默认的主键list_display('id','name','sex','profession','email','qq','phone','status','create_time')设置在列表可编辑字段list_editable
Python进阶者 Python进阶者
2年前
Excel中这日期老是出来00:00:00,怎么用Pandas把这个去除
大家好,我是皮皮。一、前言前几天在Python白银交流群【上海新年人】问了一个Pandas数据筛选的问题。问题如下:这日期老是出来00:00:00,怎么把这个去除。二、实现过程后来【论草莓如何成为冻干莓】给了一个思路和代码如下:pd.toexcel之前把这
金融科
金融科
Lv1
不必恭维不必讨好爱你的人自会给你拥抱
文章
3
粉丝
0
获赞
0