【发布时间】:2015-10-21 03:22:56
【问题描述】:
我们正在制作一个简单的脚本来浏览网站的站点地图,并获取所有链接和 href 值,然后将其保存到 .json 列表中,另一个模块可以使用该列表来截取访问过的页面.
到目前为止,我们可以让抓取列表的函数开始工作。当它在控制台运行时,我们要放入数组的数据就会显示出来。
在终端中运行时,什么都找不到,也没有填充数组。
var fs = require('fs');
var Horseman = require('node-horseman');
var horseman = new Horseman();
function findAllUrls(selector) {
var urls = [];
// get all the anchors
$(selector).each(function() {
// loop through each anchor and get the href value
var url = {
title: $(this).text(),
url: $(this).attr("href")
};
// put the href value in a new array
urls.push(url);
});
// finally return the array of all the href value
console.log("Log all urls from findAllUrls", urls);
return urls;
};
horseman
.open(URL goes here)
.evaluate(findAllUrls, '.sitemap-links a')
.then(function(urls) {
console.log(urls);
// Save the urls to a json file (lookup node 'fs' module)
fs.writeFile('urls.json', urls, function (err) {
if (err) throw err;
console.log('saved to urls.json');
});
})
.close();
运行测试时跳过了某些内容。我感觉这与 PhantomJS 模拟浏览器有关,而不是让数组通过。
【问题讨论】: