2017-09-01 64 views
1

我想要求本地JSON文件(如配置文件)並傳遞這些JSON對象來評估。對於每個配置文件,評估函數將根據配置JSON中給定的CSS選擇器返回不同的結果。Casperjs需要本地JSON文件

例如: 的文件夾結構是這樣的:

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(); 
}); 

這是我所得到的,當我嘗試運行:casperjs casperExample.js

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)我得到

SyntaxError: Expected token '}' 
C:/Users/msarc/coding/casper/rootdir/phantomjs:/platform/example.js:32 in loadModule 
C:/Users/msarc/coding/casper/rootdir/phantomjs:/platform/bootstrap.js:282 in _compile 
C:/Users/msarc/coding/casper/rootdir/phantomjs:/platform/bootstrap.js:126 in .js 
C:/Users/msarc/coding/casper/rootdir/phantomjs:/platform/bootstrap.js:278 in _load 
C:/Users/msarc/coding/casper/rootdir/phantomjs:/platform/bootstrap.js:311 in require 
C:/Users/msarc/coding/casper/rootdir/phantomjs:/platform/bootstrap.js:263 in require 
C:/Users/msarc/coding/casper/rootdir/phantomjs:/code/bootstrap.js:302 in patchedRequire 

我想最終使多個配置文件,每個不同的網站不同的選擇。 casperjs版本:1.1.4 phantomjs版本:2.1.1

回答

0

你是require ing json文件就好像它是一個javascript模塊,當然不是,所以錯誤。相反,您需要讀取該文件並將其處理爲JSON結構:

var fs = require('fs'); 
var fileContents = fs.read('config/_example.json'); 
var json = JSON.parse(fileContents); 

然後按計劃繼續工作。

+0

這工作,謝謝!但是,爲了評估JSON文件中的字符串,我使用了eval(json.title)。除了使用多個eval語句,還有其他選擇嗎? –

+0

很高興我能幫到你。如果它有效並且有幫助,爲什麼不接受答案?至於你評論中的另一個問題,我不確定你的意思。也許你可以打開另一個問題?這是關於加載JSON,我們最好堅持每個問題的一個問題。 – Vaviloff