2012-01-01 91 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); 
}); 

}