使用phantomjs进行网页抓取的实现代码


phantomjs因为是无头浏览器可以跑js,所以同样可以跑dom节点,用来进行网页抓取是再好不过了。

比如我们要批量抓取网页 “历史上的今天” 的内容。网站

对dom结构的观察发现,我们只需要取到 .list li a的title值即可。因此我们利用高级选择器构建dom片段

var d= ''
var c = document.querySelectorAll('.list li a')
var l = c.length;
for(var i =0;i<l;i++){
d=d+c[i].title+'\n'
}

之后只需要让js代码在phantomjs里跑起来即可~

var page = require('webpage').create();
	page.open('http://www.todayonhistory.com/', function (status) { //打开页面
		if (status !== 'success') {
			console.log('FAIL to load the address');
		} else {
			console.log(page.evaluate(function () {
					var d= ''
					var c = document.querySelectorAll('.list li a')
					var l = c.length;
					for(var i =0;i<l;i++){
					d=d+c[i].title+'\n'
					}
						return d
				}))

		}
		phantom.exit();
	});

最终我们另存为catch.js,在dos里面执行一下,输出内容到txt文件(也可以用phantomjs的文件api来写)


« 
» 
快速导航

Copyright © 2016 phpStudy | 豫ICP备2021030365号-3