JSON 形式の特定の URL からオンラインでリストを取得し、そのリスト内の各項目の DATA_ID を使用して新しい URL を呼び出したいと考えています。私は PhantomJS を初めて使用したばかりで、page.open() 内のネスト ループがすべて奇妙に動作する理由がわかりません。また、phantom.exit() を使用する方法は、私が達成したいことを行うのは本当に奇妙に思えます。
これが私のコードです:
console.log('Loading recipes');
console.log('===============================================================');
var page = require('webpage').create();
var url = 'http://www.hiddenurl.com/recipes/all';
page.open(url, function (status) {
//Page is loaded!
var js = page.evaluate(function () {
return document.getElementsByTagName('pre')[0];
});
var recipes = JSON.parse(js.innerHTML).results;
//console.log(recipes[0].name.replace('[s]', ''));
for (i = 0; i < recipes.length; i++) {
console.log(recipes[i].name.replace('[s]', ''));
var craft_page = require('webpage').create();
var craft_url = 'http://www.hiddenurl.com/recipe/' + recipes[i].data_id;
craft_page.open(craft_url, function (craft_status) {
//Page is loaded!
var craft_js = craft_page.evaluate(function () {
return document.getElementsByTagName('body')[0];
});
var craftp = craft_js.innerHTML;
console.log('test');
});
if (i == 5) {
console.log('===============================================================');
phantom.exit();
//break;
}
}
});
ここで起こることは、次の行です。
console.log(recipes[i].name.replace('[s]', ''));
..以下を出力します。
===============================================================
Item from DATA_ID 1
Item from DATA_ID 2
Item from DATA_ID 3
Item from DATA_ID 4
Item from DATA_ID 5
..次に、次を出力します。
===============================================================
..に続く:
'test'
'test'
'test'
'test'
'test'
これが連続して発生しないのはなぜですか?内部で呼び出された page() リクエストからのデータは、phantom.exit() が実際に呼び出された後でも、最後に積み上げられてダンプされます。
また、通常のデータセットをフリーループすると、次のエラーが発生します。
QEventDispatcherUNIXPrivate(): Unable to create thread pipe: Too many open files
2013-01-31T15:35:18 [FATAL] QEventDispatcherUNIXPrivate(): Can not continue without a thread pipe
Abort trap: 6
GLOBAL_PARAMETERS を設定したり、何らかの方法でプロセスを指示したりして、数百のページ要求を処理できる方法はありますか?
前もって感謝します!