2017-09-01 9 views
1

ローカルのJSONファイル(設定ファイルなど)を要求し、そのJSONオブジェクトを渡して評価しようとしています。各設定ファイルに対して、評価関数は、config JSONの指定されたCSSセレクタに応じて異なる結果を返します。例えばローカルJSONファイルを必要とするCasperjs

:これは私がしようとしたときに、私が得るものです

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

rootdir 
    casperExample.js 
    config/ 
    |_example.json 

example.json

{ 
    "title": "$('div.pointslocal-details-section h1').text();", 
    "date": "$('div.pointslocal-details-time p').text();" 
} 

casperExample.js: フォルダ構造は、このようなものです実行する:casperjs casperExample.js

CasperError: Can't find module ./config/example.json 
    C:/Users/msarc/coding/casper/rootdir/phantomjs:/code/bootstrap.js:307 in patchedRequire 

と私は(.jsonなし)var json = require('./config/example');を使用する場合、私は私が最終的には、複数の設定ファイルを作りたい

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です.jsonファイルは、あたかもjavascriptモジュールであるかのように扱われています。それはもちろんエラーではありません。代わりにファイルを読み込んで処理する必要があります。

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

次に計画どおりに作業を進めてください。

+0

これは、感謝しました!しかし、JSONファイルから文字列を評価するために、私はeval(json.title)を使用しています。複数のeval文を使用する代わりに使用できますか? –

+0

私は助けてよかった。それがうまくいって助けになった場合は、その答えを受け入れないでください。あなたのコメントの別の質問については、私はあなたが何を意味するか分からない。多分あなたは別の質問を開くことができますか?これはJSONの読み込みに関するもので、各質問ごとに1つの問題に固執するのがよいでしょう。 – Vaviloff

関連する問題