PhantomJS 2.0.0不会等待页面加载

PhantomJS 2.0.0 doesn't wait for page to load

本文关键字:等待 加载 PhantomJS      更新时间:2023-09-26

下面的脚本包含links数组中的一些url。gatherLinks()函数用于从sitemap.xml中收集links数组中的url。一旦links数组有足够的URL(由变量limit决定),就调用request()函数为links数组中的每个URL发送请求到服务器,获取响应并使用page.render()函数保存图像。

问题是,当我使用PhantomJS 2.0.0运行它时,许多图像缺乏大量内容,即PhantomJS可能不会等待所有内容加载。但是当我使用PhantomJS 1.9.8时,所有内容都加载得很好。原因是什么呢?

var webpage = require('webpage');
var system = require('system');
var fs = require('fs');
var links = [];
links = [
    "http://somesite.com",
    "http://someothersite.com",
       . 
       .
       .
 ];
var index = 0, fail = 0, limit = 20;
finalTime = Date.now();
var gatherLinks = function(link){
  var page = webpage.create();
  link = link + "/sitemap.xml";
  console.log("Fetching links from " + link);
  page.open(link, function(status){
    if(status != "success"){
      console.log("Sitemap Request FAILED, status: " + status);
      fail++;
      return;
    }
    var content = page.content;
    parser = new DOMParser();
    xmlDoc = parser.parseFromString(content, 'text/xml');
    var loc = xmlDoc.getElementsByTagName('loc');
    for(var i = 0; i < loc.length; i++){
      if(links.length < limit){
        links[links.length] = loc[i].textContent;
      } else{
        console.log(links.length + " Links prepared. Starting requests.'n");
        index = 0;
        page.close();
        request();
        return;
      }
    }
    if(index >= links.length){
      index = 0;
      console.log(links.length + " Links prepared'n'n");
      page.close();
      request();
      return;
    }
    page.close();
    gatherLinks(links[++index]);
  });
};
var request = function(){
  t = Date.now();
  var page = webpage.create();
  page.open(links[index], function(status) {
    console.log('Loading link #' + (index + 1) + ': ' + links[index]);
    console.log("Time taken: " + (Date.now() - t) + " msecs");
    if(status != "success"){
      console.log("Request FAILED, status: " + status);
      fail++;
    }
    page.render("img_200_" + index + ".jpeg", {format: 'jpeg', quality: '100'});
    if(index >= links.length-1){
      console.log("'n'nAll links done, final time taken: " + (Date.now() - finalTime) + " msecs");
      console.log("Requests sent: " + links.length + ", Failures: " + fail);
      console.log("Success ratio: " + ((links.length - fail)/links.length)*100 + "%");
      page.close();
      phantom.exit();
    }
    index++;
    page.close();
    request();
  });
}
gatherLinks(links[0]);

PhantomJS没有定义在页面加载过程中何时调用page.open回调。因此,实际上并没有什么错误的主张。

可以使用setTimeout()添加静态等待量,这应该有助于动态站点。还有一些方法可以通过计算使用page.onResourceRequested发送了多少请求以及使用page.onResourceReceived/page.onResourceTimeout/page.onResourceError完成了多少请求来查看是否有待处理请求。

如果它实际上是一个PhantomJS bug,那么除了尝试一些命令行开关之外,没有太多的方法。