官术网_书友最值得收藏!

Writing PhantomJS scripts

We know how to write JavaScript, and now we know that there are several PhantomJS JavaScript APIs and objects. We also have learned the basics of the PhantomJS command-line arguments. We are now ready to create our own scripts.

We will create a simple script to load a site and then display the title of the page when loaded successfully. Finally, we will exit. If the page fails to load, we will log some message to the console.

var page = require('webpage').create();
page.open("http://www.packtpub.com", function(status) {
   if ( status === "success" ) {
      console.log(page.title); 
   } else {
      console.log("Page failed to load."); 
   }
   phantom.exit(0);
});

The preceding PhantomJS script is very simple. First, we import the webpage module, create an instance of the webpage object, and assign it to a variable named page.

The page variable now holds an instance of the webpage module where an open function is available. Next, we instructed PhantomJS through the webpage instance to open and load the URL. The second parameter of the open function is a function callback definition that will be executed upon completion of the opening of the URL. Inside the definition, we check if the status is "success", and if it is, the page is loaded, and then we will display the title of the page. Then, we call the exit function to terminate the script. Let's save this code snippet as helloweb.js and execute it by passing the filename as our first argument to the phantomjs binary.

Writing PhantomJS scripts
主站蜘蛛池模板: 南投县| 朝阳县| 富平县| 柯坪县| 南京市| 曲阜市| 壶关县| 福贡县| 玉田县| 塘沽区| 怀柔区| 都安| 香港 | 花垣县| 汉川市| 大理市| 报价| 璧山县| 江山市| 化州市| 灵川县| 弥勒县| 罗源县| 天台县| 中西区| 大冶市| 突泉县| 延川县| 曲周县| 太仆寺旗| 萨嘎县| 五河县| 盐边县| 留坝县| 个旧市| 丰原市| 鲁甸县| 衡东县| 巴林右旗| 方山县| 苏尼特左旗|