Web自动化之Headless Chrome开发工具库

2017-07-02  本文已影响0人  淼焱洞见

命令行运行Headless Chrome

Chrome 安装(需要带梯子)

命令行快捷配置(Mac环境)

~/.bashrc 中加入

alias chrome="/Applications/Google\ Chrome.app/Contents/MacOS/Google\ Chrome"
alias chrome-canary="/Applications/Google\ Chrome\ Canary.app/Contents/MacOS/Google\ Chrome\ Canary"

重新打开终端,我们就可以直接通过 chrome打开稳定版的Chrome,chrome-canary打开试验版的Chrome了。

命令行启动Chrome

命令行操作Headless Chrome

可编程方式运行Headless Chrome

直接通过代码调用命令行启动Chrome 调试Server

可以通过系统调用的方式直接调用上面的命令行执行方式。这种方式在跨平台的情况下会有一些工作需要做。

Google出品的Lighthouse 这个网页质量检查工具,有一个组件专门做这事,考虑了各种平台的兼容性问题,源码参考lighthouse-chromelauncher,这个组件现在已经单独独立出来,作为一个单独的NPM组件chrome-launcher,可以直接使用这个在Node平台下调用,其他平台的也可以此为参考。

const chromeLauncher = require('chrome-launcher');
//启用无界面模式并开启远程调试,不同引用版本和方式,调用方式可能有些区别
//chromeLauncher.run({
chromeLauncher.launch({
    // port: 9222,
    chromeFlags: [
        '--headless'
    ]
}).then((chrome) => {
    // 拿到一个调试客户端实例
    console.log(chrome)
    chrome.kill();
});

通过客户端的封装组件进行浏览器交互

实现了ChromeDevTools协议的工具库有很多chrome-remote-interface是NodeJS的实现。

Chrome调试Server开启的是WebSocket交互的相关实现,要用编程的方式实现还需要封装一些WebSocket命令发送、结果接收等这一系列操作,这些chrome-remote-interface已经帮我们做了,更多实例可以参考chrome-remote-interface的wiki

const chromeLauncher = require('chrome-launcher');
const chromeRemoteInterface = require('chrome-remote-interface')
//启用无界面模式并开启远程调试,不同引用版本和方式,调用方式可能有些区别
//chromeLauncher.run({
chromeLauncher.launch({
    port: 9222,
    chromeFlags: [
        '--headless'
    ]
}).then((launcher) => {
    chromeRemoteInterface.Version({
        host:'localhost',
        port:9222
    }).then(versionInfo => {
        console.log(versionInfo)
    });

    chromeRemoteInterface({
        host:'localhost',
        port:9222
    }).then((chrome) => {
        //这里调用ChromeDevToolsProtocol定义的接口
        const {Network,Page} = chrome;

        Network.requestWillBeSent((params) => {
            let {request}  = params;
            let {url} = request;
            console.log(url)
        });
        Promise.all([
            Network.enable(),
            Page.enable()
        ]).then(() => {
            Page.navigate({
                url:'https://www.baidu.com'
            })
        });

        setTimeout(() => {
            launcher.kill()
        },5000);

    })
});
上一篇 下一篇

猜你喜欢

热点阅读