我第一次嘗試了phantomJS,並且我已經成功地從站點提取了som數據,但是當我嘗試向文件寫入一些內容時,出現錯誤:ReferenceError:Can not找到變量:FSPhantomJS寫入文件fs的問題。找不到變量:fs
這裏是我的腳本
var page = require('webpage').create();
var fs = require('fs');
page.onConsoleMessage = function(msg) {
console.log(msg);
};
page.open("http://www.pinterest.com/search/pins/?q=motorbike", function(status) {
if (status === "success") {
page.includeJs("http://code.jquery.com/jquery-latest.js", function() {
page.evaluate(function() {
var imgs = {
title: [],
href: [],
ext: [],
src: [],
alt: []
};
$('a.pinImageWrapper').each(function() {
imgs.title.push($(this).attr('title'));
imgs.href.push($(this).attr('href'));
var ext = $(this).children('.pinDomain').html();
imgs.ext.push(ext);
var img = $(this).children('.fadeContainer').children('img.pinImg');
imgs.src.push(img.attr('src'));
imgs.alt.push(img.attr('alt'));
});
if (imgs.title.length >= 1) {
for (var i = 0; i < imgs.title.length; i++) {
console.log(imgs.title[i]);
console.log(imgs.href[i]);
console.log(imgs.ext[i]);
console.log(imgs.src[i]);
console.log(imgs.alt[i]);
}
} else {
console.log('No pins found');
}
fs.write('foo.txt', 'bar');
});
phantom.exit();
});
}
});
缺少什麼我在這裏?
編輯:在這個問題的答案我知道爲什麼我無法達到評估內的數據,以及我如何訪問它。
var page = require('webpage').create();
var fs = require('fs');
page.onConsoleMessage = function(msg) {
console.log(msg);
};
openPinPage('motorbike');
function openPinPage(keyword) {
page.open("http://www.pinterest.com/search/pins/?q=" + keyword, function(status) {
if (status === "success") {
page.includeJs("http://code.jquery.com/jquery-latest.js", function() {
getImgsData();
});
}
});
}
function getImgsData() {
var data = page.evaluate(function() {
var imgs = {
title: [],
href: [],
ext: [],
src: [],
alt: []
};
$('a.pinImageWrapper').each(function() {
imgs.title.push($(this).attr('title'));
imgs.href.push($(this).attr('href'));
var ext = $(this).children('.pinDomain').html();
imgs.ext.push(ext);
var img = $(this).children('.fadeContainer').children('img.pinImg');
imgs.src.push(img.attr('src'));
imgs.alt.push(img.attr('alt'));
});
return imgs;
});
for (var i = 0; i < data.title.length; i++) {
console.log(data.title[i]);
};
phantom.exit();
}
我已經添加了一個答案,顯示如何編寫一些網頁內容到文件。 – Mritunjay