phantomjs 抓取搜狗相关搜索的例子
phantomjs 是一个具有webkit内核的无界面浏览器,有很多强大的功能,做爬虫也是很简单的(当然是简单的爬虫),
这是一个爬取搜狗相关搜索的例子,可以多加点东西,或者改成爬取其他网页的爬虫:
var page = require('webpage').create(); var system = require('system'); if (system.args.length != 2) { console.log("input keyword to search!"); } else { // 设置编码一般使用System不会出错 utf8反而不给力 phantom.outputEncoding = 'System'; // 通过命令行读取搜索参数 address = encodeURI('http://www.sogou.com/web?query=' + system.args[1]); console.log(address); try { var openbaidu = page.open(address, function(status) { var title = page.evaluate(function() { // WebKit接口 var res = document.querySelectorAll('#hint_container a'); var res_text = ''; for (i = 0; i < res.length; i++) { res_text += res[i].innerHTML + "\n"; } return res_text; }); console.log(title); }); openbaidu; } catch (e) { console.log(e); } }
使用实例: