关注phantomjs比较早,以前也作过一些学习总结,但是一直都没写博客,这里再记录下。为了让同事也开始学习了解下, 提供了一个demo,固然,这个demo也是根据一些资料整理而来。
这个demo很简单,就是访问百度,而后输入关键字,提交表单,而后获取部分结果javascript
system = require('system') var page = require('webpage').create(); phantom.outputEncoding = 'gb2312'; page.settings = { javascriptEnabled: true, loadImages: true, userAgent: 'Mozilla/5.0 (Windows NT 10.0; WOW64; rv:43.0) Gecko/20100101 Firefox/43.0' }; todo: var t_key_word = ''; if (system.args.length === 1) { phantom.exit(1); } else { t_key_word = system.args[1]; console.log("search keyword " + t_key_word + " from www.baidu.com"); } console.log(t_key_word) testindex = 0, loadInProgress = false; page.onConsoleMessage = function (msg) { console.log(msg); }; page.onLoadStarted = function () { loadInProgress = true; console.log("load started"); }; page.onLoadFinished = function () { loadInProgress = false; console.log("load finished"); }; var steps = [ //open url function () { page.open("http://www.baidu.com"); }, //enter input function () { page.render("step1-1.png"); page.evaluate(function (key_word) { console.log("*****************************"); var kw = document.getElementById('kw'); kw.value = key_word; return; }, t_key_word); page.render("step1-2.png"); }, //submit function () { page.evaluate(function () { var search_btn = document.getElementById('su'); search_btn.click(); return; }); page.render("step2.png"); }, //get search result function () { var content_rst = page.evaluate(function () { var rst = new Array(); var len = document.getElementsByTagName('h3').length; for (i = 0; i < len; i++) { rst[i] = document.getElementsByTagName('h3')[i].innerHTML; } return rst; }); console.log(content_rst); } ]; interval = setInterval(function () { if (!loadInProgress && typeof steps[testindex] == "function") { console.log("step " + (testindex + 1)); steps[testindex](); testindex++; } if (typeof steps[testindex] != "function") { console.log("test complete!"); phantom.exit(); } }, 2000);
另存为test.js
而后执行phantomjs test.js javascript
就会搜索javascript关键字java
须要注意的地方是:
page.evaluate会启动一个sandbox来执行js, 因此里面的参数不能直接从外面获取,不过还好evaluate接受两个参数,第一个是必需的,表示须要在page上下文运行的函数 function;第二个是可选的,表示须要传给 function的参数 param,好比上面的key_worldweb