我是第一次尝试phantomJS并且我已成功从站点中提取som数据,但是当我尝试将某些内容写入文件时,我得到错误:ReferenceError:找不到变量: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: [],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(); }
解决方法
你不能在page.evaluate中拥有phantomjs对象,因为那是一个网页.我将举一个简单的例子,说明你如何实现自己的目标.
如果要在文件中编写某些网页内容,则必须从page.evaluate返回这些标记.你将在page.open中获得这些值.在这里您可以访问fs,因此您可以编写这些内容.
page.open("http://www.pinterest.com/search/pins/?q=motorbike",function() { var title = page.evaluate(function() { return document.title; // here I don't have access to fs I'll return title of document from here. }); console.log(title) //I got the title now I can write here. fs.write('foo.txt',title); phantom.exit(); }); } });