Casperjs需要本地JSON文件
我试图要求本地JSON文件(如配置文件)并传递这些JSON对象进行计算。对于每个配置文件,evaluate函数将根据config JSON中给定的CSS选择器返回不同的结果 例如: 文件夹结构如下所示:Casperjs需要本地JSON文件,json,phantomjs,casperjs,require,evaluate,Json,Phantomjs,Casperjs,Require,Evaluate,我试图要求本地JSON文件(如配置文件)并传递这些JSON对象进行计算。对于每个配置文件,evaluate函数将根据config JSON中给定的CSS选择器返回不同的结果 例如: 文件夹结构如下所示: rootdir casperExample.js config/ |_example.json example.json { "title": "$('div.pointslocal-details-section h1').text();", "date":
rootdir
casperExample.js
config/
|_example.json
example.json
{
"title": "$('div.pointslocal-details-section h1').text();",
"date": "$('div.pointslocal-details-time p').text();"
}
casperExample.js
var casper = require('casper').create();
var require = patchRequire(require);
var json = require('./config/example.json');
casper.start('https://website/to/be/scraped');
casper.then(function(){
this.echo(json);
pageData = this.evaluate(function(json){
var results = {};
results['title'] = json.title;
results['date'] = json.date;
return results;
}, json);
this.echo(pageData);
});
casper.run(function(){
this.exit();
});
CasperError: Can't find module ./config/example.json
C:/Users/msarc/coding/casper/rootdir/phantomjs:/code/bootstrap.js:307 in patchedRequire
这是我尝试运行时得到的结果:casperjs casperExample.js
var casper = require('casper').create();
var require = patchRequire(require);
var json = require('./config/example.json');
casper.start('https://website/to/be/scraped');
casper.then(function(){
this.echo(json);
pageData = this.evaluate(function(json){
var results = {};
results['title'] = json.title;
results['date'] = json.date;
return results;
}, json);
this.echo(pageData);
});
casper.run(function(){
this.exit();
});
CasperError: Can't find module ./config/example.json
C:/Users/msarc/coding/casper/rootdir/phantomjs:/code/bootstrap.js:307 in patchedRequire
如果我使用var json=require('./config/example')代码>(不带.json)我得到
我想最终制作多个配置文件,每个文件都有不同网站的不同选择器。casperjs版本:1.1.4 phantomjs版本:2.1.1您需要
将json文件当作javascript模块来处理,当然不是这样,因此出现了错误。相反,您需要读取文件并处理它的JSON结构:
var fs = require('fs');
var fileContents = fs.read('config/_example.json');
var json = JSON.parse(fileContents);
然后按计划继续工作。您需要像处理javascript模块一样处理json文件,当然不是,因此出现了错误。相反,您需要读取文件并处理它的JSON结构:
var fs = require('fs');
var fileContents = fs.read('config/_example.json');
var json = JSON.parse(fileContents);
然后按计划继续工作。这成功了,谢谢!但是,为了计算JSON文件中的字符串,我使用eval(JSON.title)。除了使用多个eval语句,还有其他选择吗?很高兴我能提供帮助。如果它起作用并且有帮助,为什么不接受这个答案呢?至于你评论中的另一个问题,我不知道你的意思。也许你可以再问一个问题?这是关于加载JSON的,我们最好每个问题只讨论一个问题。这很有效,谢谢!但是,为了计算JSON文件中的字符串,我使用eval(JSON.title)。除了使用多个eval语句,还有其他选择吗?很高兴我能提供帮助。如果它起作用并且有帮助,为什么不接受这个答案呢?至于你评论中的另一个问题,我不知道你的意思。也许你可以再问一个问题?这是关于加载JSON的,我们最好每个问题只讨论一个问题。