Phantomjs-page-automation

提供:Dev Guides
移動先:案内検索

PhantomJS-ページ自動化

PhantomJSは、そのWebページモジュールAPIを使用して、Webページを操作し、DOM操作、ボタンのクリックなどの操作を実行できます。

ページから画像を取得する

次のプログラムは、PhantomJSを使用してページから画像を取得する方法を示しています。

var wpage = require('webpage').create();
wpage.onConsoleMessage = function(str) {
   console.log(str.length);
}
wpage.open("http://phantomjs.org", function(status) {
   console.log(status);
   var element = wpage.evaluate(function() {
      var imgdata =  document.querySelectorAll('img');
      var imgsrc = [];

      if (imgdata) {
         for (var i in imgdata) {
            imgsrc.push(imgdata[0].src);
         }
      }
      return imgsrc;
   });
   console.log(JSON.stringify(element));
});

上記のプログラムは、次の output を生成します。

Success
["http://phantomjs.org/img/phantomjslogo.png","http://phantomjs.org/img/phantom
js-logo.png","http://phantomjs.org/img/phantomjslogo.png","http://phantomjs.org
/img/phantomjs-logo.png"]
*injectJS webpage method* を使用して、外部JavaScriptをページに含めることができます。 多くのプロパティとメソッドがあり、ページの自動化に役立ち、他の多くのことを実行できます。 プロパティとメソッドが詳細に説明されているWebページモジュールを参照できます。