Node+Nightmare超爽瀏覽器自動化開發

緣起

一直想作一個無界面瀏覽器自動化的工具,用來實現三個小目標:node

  • 完善的CSS,JS,SVG支持,抓取渲染後的頁面,實現截圖
  • 實現必要的頁面交換,好比按鈕點擊,表單填寫
  • 無界面運行,跨平臺

一通搜索以後,這個列表真的很詳細了,列出了各類語言實現的無界面瀏覽器,基本都沒有用過,只能根據開發的活躍度和github的星星數作一個簡單篩選, Phantomjs和Nightmare進入了候選。Phantomjs以前接觸過,思路仍是很直接的,就是用js驅動webkit瀏覽器核心,星星1w+了,挺靠譜的應該。可是API真的比較原始,Nightmare最初應該是對Phantomjs的一次封裝,從零星的網絡介紹文章能夠了解到這一點。上github主頁看了看,8千多的星星,也不錯。另一個重大發現是已經和Phantomjs分道揚鑣了,用了Electron這個當紅炸子雞,Phantomjs儼然被它推到了對立面,主頁上正是兩個工具的代碼對比:git

phantom.create(function (ph) {
  ph.createPage(function (page) {
    page.open('http://yahoo.com', function (status) {
      page.evaluate(function () {
        var el =
          document.querySelector('input[title="Search"]');
        el.value = 'github nightmare';
      }, function (result) {
        page.evaluate(function () {
          var el = document.querySelector('.searchsubmit');
          var event = document.createEvent('MouseEvent');
          event.initEvent('click', true, false);
          el.dispatchEvent(event);
        }, function (result) {
          ph.exit();
        });
      });
    });
  });
});

看着嵌套,唉,是否是有點暈了。再看Nightmare的:github

yield Nightmare()
  .goto('http://yahoo.com')
  .type('input[title="Search"]', 'github nightmare')
  .click('.searchsubmit');

是否是很簡單?!web

另外,安裝也很簡潔,npm install nightmare 牆內的朋友若是npm安裝不成功,就試試cnpm吧,安裝 請看:https://npm.taobao.org/npm

小試牛刀

由於nightmare是node驅動其工做,npm init 建立項目後,添加nightmare依賴,就能夠開始編寫node腳本,驅動Electron瀏覽器幹活啦。登錄OSC,只需幾行代碼搞定:瀏覽器

var Nightmare = require('nightmare');
var nightmare = Nightmare({ show: false });

nightmare
  .goto('https://www.oschina.net/')
  .wait('footer')
  .exists('div.user-info')
  .then(function (result) {    
    if(!result)
    {
      return nightmare
        .goto("https://www.oschina.net/home/login")
        .wait("div.login-form")
        .type("#userMail","紅薯@oschina.net")
        .type("#userPassword","hahaha")
        .click("button.btn-login")
        .wait(5000)
        .exists("div.user-info")
    }
    else
    {
      console.log("已是登錄狀態了,不用登錄");
      return nightmare.end();    
    }
  })
  .then(function(result) {
      if(result && result == true)
      {
        console.log("登錄成功!")
        return nightmare.end();
      }
      else
      {
        console.error('登錄失敗');
      }
  })
  .catch(function (error) {
    console.error('異常:', error);
  });

是否是代碼都通俗易懂?網絡

深刻了解

文檔已經比較清楚了:Github 文檔 另外再看看幾個例子:Examplesless

調試

我的在選型的時候,會很在乎調試是否方便,不能斷點調試的,都會自動進入待定區,打上一個問號。Nightmare,配合VSCode,調試實在太方便。ssh

  • 直接F5,選Nodejs腳本,而後配置下launch.js裏的入口文件,設置斷點
  • var nightmare = Nightmare({ show: true}); //true表示顯示Electron瀏覽器
  • 啓動調試,瀏覽器就跳出來了,按照腳本一步步運行,在斷點就停下來了

結束語

本人接觸Nightmare也就3天時間,深感這是一個好用的工具,又以爲中文的介紹都很舊了,因此寫下這篇博文,但願拋磚引玉,你們共同研究,一塊兒提升!工具

相關文章
相關標籤/搜索