Web自動化之Headless Chrome編碼實戰

API 概覽 && 編碼Tips

文檔地址

常用API

  • Network 網絡請求、Cookie、緩存、證書等相關內容
  • Page 頁面的加載、資源內容、彈層、截圖、打印等相關內容
  • DOM 文檔DOM的獲取、修改、刪除、查詢等相關內容
  • Runtime JavaScript代碼的執行,這里面我們可以搞事情~~

編碼Tips

  • 我們這里不會直接調用Websocket相關的內容來調用chrome的調試命令,而是用chrome-remote-interface 這個封裝的庫來做,它是基于Promise風格的
  • 每一個功能塊成為一個單獨的domain,像Network,Page,DOM等都是不同的domain
  • 幾乎每一個個頭大的domain都有enable方法,需要先調用這個方法啟用之后再使用
  • 各個domain的接口方法參數都是第一個對象或者說一個Map,不用考慮參數的位置了
  • 各個domain的接口返回值也是一個對象,取對應的key就行
  • 參數值和返回值經常是meta信息,經常是各種對象的id信息,而不是具體的對象內容(這里可能需要切一下風格)

編碼實例

首先做一個簡單的封裝,準備API的執行環境,具體可參考前一篇關于工具庫的。

const chromeLauncher = require('chrome-launcher');
const chromeRemoteInterface = require('chrome-remote-interface');

const prepareAPI = (config = {}) => {
    const {host = 'localhost', port = 9222, autoSelectChrome = true, headless = true} = config;
    const wrapperEntry = chromeLauncher.launch({
        host,
        port,
        autoSelectChrome,
        additionalFlags: [
            '--disable-gpu',
            headless ? '--headless' : ''
        ]
    }).then(chromeInstance => {
        const remoteInterface = chromeRemoteInterface(config).then(chromeAPI => chromeAPI).catch(err => {
            throw err;
        });
        return Promise.all([chromeInstance, remoteInterface])
    }).catch(err => {
        throw err
    });

    return wrapperEntry
};

打開百度,獲取頁面性能數據,參考 Navigation Timing W3C規范

const wrapper = require('the-wrapper-module');

const performanceParser = (perforceTiming) => {
    let timingGather = {};
    perforceTiming = perforceTiming || {};
    timingGather.redirect = perforceTiming.redirectEnd - perforceTiming.redirectEnd-perforceTiming.redirectStart;
    timingGather.dns = perforceTiming.domainLookupEnd - perforceTiming.domainLookupStart;
    timingGather.tcp = perforceTiming.connectEnd - perforceTiming.connectStart;
    timingGather.request = perforceTiming.responseStart - perforceTiming.requestStart;
    timingGather.response = perforceTiming.responseEnd - perforceTiming.responseStart;
    timingGather.domReady = perforceTiming.domContentLoadedEventStart - perforceTiming.navigationStart;
    timingGather.load = perforceTiming.loadEventStart - perforceTiming.navigationStart;
    return timingGather;
};

const showPerformanceInfo = (performanceInfo) => {
    performanceInfo = performanceInfo || {};
    console.log(`頁面重定向耗時:${performanceInfo.redirect}`);
    console.log(`DNS查找耗時:${performanceInfo.dns}`);
    console.log(`TCP連接耗時:${performanceInfo.tcp}`);
    console.log(`請求發送耗時:${performanceInfo.request}`);
    console.log(`響應接收耗時:${performanceInfo.response}`);
    console.log(`DOMReady耗時:${performanceInfo.domReady}`);
    console.log(`頁面加載耗時:${performanceInfo.load}`);
};

wrapper.prepareAPI().then(([chromeInstance, remoteInterface]) => {
    const {Runtime,Page} = remoteInterface;

    Page.loadEventFired(() => {
        Runtime.evaluate({
            expression:'window.performance.timing.toJSON()',
            returnByValue:true  //不加這個參數,拿到的是一個對象的meta信息,還需要getProperties
        }).then((resultObj) => {
            let {result,exceptionDetails} = resultObj;
            if(!exceptionDetails){
                showPerformanceInfo(performanceParser(result.value))
            }else{
                throw exceptionDetails;
            }
        });
    });

    Page.enable().then(() => {
        Page.navigate({
            url:'http://www.baidu.com'
        })
    });
});

打開百度 搜索Web自動化 headless chrome,并爬取首屏結果鏈接

const wrapper = require('the-wrapper-module');
//有this的地方寫成箭頭函數要注意,這里會有問題
const buttonClick = function () {
    this.click();
};

const setInputValue = () => {
    var input = document.getElementById('kw');
    input.value = 'Web自動化 headless chrome';
};

const parseSearchResult = () => {
    let resultList = [];
    const linkBlocks = document.querySelectorAll('div.result.c-container');
    for (let block of Array.from(linkBlocks)) {
        let targetObj = block.querySelector('h3');
        resultList.push({
            title: targetObj.textContent,
            link: targetObj.querySelector('a').getAttribute('href')
        });
    }
    return resultList;
};


wrapper.prepareAPI({
    // headless: false  //加上這行代碼可以查看瀏覽器的變化
}).then(([chromeInstance, remoteInterface]) => {
    const {Runtime, DOM, Page, Network} = remoteInterface;
    let framePointer;
    Promise.all([Page.enable(), Network.enable(), DOM.enable(),Page.setAutoAttachToCreatedPages({autoAttach:true})]).then(() => {
        Page.domContentEventFired(() => {
            console.log('Page.domContentEventFired')
            Runtime.evaluate({
                expression:`window.location.href`,
                returnByValue:true
            }).then(result => {
                console.log(result)
            })
        });
        Page.frameNavigated(() => {
            console.log('Page.frameNavigated')
            Runtime.evaluate({
                expression:`window.location.href`,
                returnByValue:true
            }).then(result => {
                console.log(result)
            })
        })
        Page.loadEventFired(() => {
            console.log('Page.loadEventFired')
            Runtime.evaluate({
                expression:`window.location.href`,
                returnByValue:true
            }).then(result => {
                console.log(result)
            })
            DOM.getDocument().then(({root}) => {
                //百度首頁表單
                DOM.querySelector({
                    nodeId: root.nodeId,
                    selector: '#form'
                }).then(({nodeId}) => {
                    Promise.all([
                        //找到 搜索框填入值
                        DOM.querySelector({
                            nodeId: nodeId,
                            selector: '#kw'
                        }).then((inputNode) => {

                            Runtime.evaluate({
                                // 兩種寫法
                                // expression:'document.getElementById("kw").value = "Web自動化 headless chrome"',
                                expression: `(${setInputValue})()`
                            });


                            //這段代碼不起作用 日狗
                            // DOM.setNodeValue({
                            //     nodeId:inputNode.nodeId,
                            //     value:'Web自動化 headless chrome'
                            // });

                            //上面的代碼需求要這么寫
                            // DOM.setAttributeValue({
                            //     nodeId:inputNode.nodeId,
                            //     name:'value',
                            //     value:'headless chrome'
                            // });
                        })
                        //找到 提交按鈕setInputValue
                        , DOM.querySelector({
                            nodeId,
                            selector: '#su'
                        })
                    ]).then(([inputNode, buttonNode]) => {

                        Runtime.evaluate({
                            expression: 'document.getElementById("kw").value',
                        }).then(({result}) => {
                            console.log(result)
                        });

                        return DOM.resolveNode({
                            nodeId: buttonNode.nodeId
                        }).then(({object}) => {
                            const {objectId} = object;
                            return Runtime.callFunctionOn({
                                objectId,
                                functionDeclaration: `${buttonClick}`
                            })
                        });
                    }).then(() => {
                        setTimeout(() => {
                            Runtime.evaluate({
                                expression: `(${parseSearchResult})()`,
                                returnByValue: true
                            }).then(({result}) => {
                                console.log(result.value)
                                //百度的URL有加密,需要再請求一次拿到真實URL
                            })
                        },3e3)
                    });
                })

            });
        });
        Page.navigate({
            url: 'http://www.baidu.com'
        }).then((frameObj) => {
            framePointer = frameObj
        });
    })

});
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容

  • Android 自定義View的各種姿勢1 Activity的顯示之ViewRootImpl詳解 Activity...
    passiontim閱讀 173,447評論 25 708
  • 1. Java基礎部分 基礎部分的順序:基本語法,類相關的語法,內部類的語法,繼承相關的語法,異常的語法,線程的語...
    子非魚_t_閱讀 31,767評論 18 399
  • Spring Cloud為開發人員提供了快速構建分布式系統中一些常見模式的工具(例如配置管理,服務發現,斷路器,智...
    卡卡羅2017閱讀 134,973評論 19 139
  • 【本我自我超我】 大象和騎象人的心理模型其實是潛意識和自我的博弈。本我總是想要讓身體更舒服、更安逸,讓身體的欲望得...
    蝎子小貓咪閱讀 2,147評論 3 8
  • 年少未嘗把吳鉤,踏馬雄心非無有。 古文哲士旅學游,積沉勃發天下求。 愚生數載校園寄,何曾鍛磨心力籌。 今日輕別致牽...
    村客閱讀 280評論 0 8