phantomjs应用(一)
关注phantomjs比较早,之前也做过一些学习总结,可是一直都没写博客,这里再记录下。为了让同事也开始学习了解下, 提供了一个demo,当然,这个demo也是根据一些资料整理而来。
这个demo很简单,就是访问百度,然后输入关键字,提交表单,然后获取部分结果
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关键字
需要注意的地方是:
page.evaluate会启动一个sandbox来执行js, 所以里面的参数不能直接从外面获取,不过还好evaluate接受两个参数,第一个是必需的,表示需要在page上下文运行的函数 function;第二个是可选的,表示需要传给 function的参数 param,比如上面的key_world
相关推荐
littleFatty 2020-08-16
Aveiox 2020-06-23
archimedes 2020-05-27
zrtlin 2020-11-09
xuebingnan 2020-11-05
wikiwater 2020-10-27
heheeheh 2020-10-19
Crazyshark 2020-09-15
softwear 2020-08-21
ZGCdemo 2020-08-16
jczwilliam 2020-08-16
idning 2020-08-03
jinxiutong 2020-07-26
lanzhusiyu 2020-07-19
Skyline 2020-07-04
xiaofanguan 2020-06-25