2012-01-01 28 views
6

Digikey改變了他們的網站,現在有一個javascript,通過發佈被稱爲onload。這造成了我以前的簡單的Java代碼檢索器。我試圖使用PhantomJS來允許在保存HTML /文本之前執行JavaScript。PhantomJS頁面轉儲腳本問題

var page = new WebPage(), 
t, address; 


var fs = require('fs'); 

if (phantom.args.length === 0) { 

console.log('Usage: save.js <some URL>'); 
phantom.exit(); 
} else { 

address = encodeURI(phantom.args[0]); 
page.open(address, function (status) { 
    if (status !== 'success') { 
     console.log('FAIL to load the address'); 
    } else { 
     f = null; 
     var markup = page.content; 
     console.log(markup); 
     try { 
     f = fs.open('htmlcode.txt', "w"); 
     f.write(markup); 
     f.close();   
     } catch (e) { 
      console.log(e); 
     } 
    } 
    phantom.exit(); 

}); 

} 

此代碼適用於大多數的網頁,但未能上:

http://search.digikey.com/scripts/dksearch/dksus.dll?keywords=S7072-ND

這是我的測試情況。它無法打開URL,然後PhantomJS崩潰。使用win32靜態構建1.3。

任何提示?

基本上我之後是wget,它在保存文件之前競爭頁面渲染和修改文檔的腳本。

回答

1

一個快速的骯髒的解決方案...然後張貼在phantomjs網站...是使用超時。我已經修改了你的代碼以包含2秒鐘的等待時間。這允許頁面在將內容轉儲到文件之前加載2秒。如果您需要準確的秒數或時間量差別很大,則此解決方案可能無法爲您工作。

var page = new WebPage(), 

t, address; 


var fs = require('fs'); 

if (phantom.args.length === 0) { 

console.log('Usage: save.js <some URL>'); 
phantom.exit(); 
} else { 

address = encodeURI(phantom.args[0]); 
page.open(address, function (status) { 
    if (status !== 'success') { 
     console.log('FAIL to load the address'); 
    } else { 
     window.setTimeout(function(){ 
      f = null; 
      var markup = page.content; 
      console.log(markup); 
      try { 
      f = fs.open('htmlcode.txt', "w"); 
      f.write(markup); 
      f.close();   
      } catch (e) { 
       console.log(e); 
      } 
     } 
     phantom.exit(); 
    },2000); 
}); 

}