2013-04-28 75 views
2

我試圖使用phantomjs來屏幕捕獲我的頁面與node-phantom橋樑。這是我想要的:page.set('content')不適用於phantomjs中的動態內容

var phantom = require('node-phantom'); 

phantom.create(function (err, ph) { 
      return ph.createPage(function (err, page) { 
       return page.set('content', '<html><head></head><body><p>Hello</p></body></html>', function (err, status) { 
        return page.render('./content.png', function (err) { 
        ph.exit(); 
        }); 
       }); 
      }); 
      }); 

這工作正常,但如果我嘗試設置包含JavaScript的內容,這是行不通的。請幫助我,爲什麼它不起作用?

編輯:這不起作用:

var phantom = require('node-phantom'); 

phantom.create(function (err, ph) { 
    return ph.createPage(function (err, page) { 
     page.open("about:blank", function(err,status) { 
     page.evaluate(function() {   
      document.write('<html><head></head><body><script src="http://code.jquery.com/jquery-1.9.1.min.js"></script><script>$(function(){document.write("Hello from jQuery")})</script></body>'); 
     }); 

     setTimeout(function() { 
      return page.render('./content.png', function (err) { 
       ph.exit(); 
      }); 
     }, 5000); 
    });   
    }); 

回答

0

我不知道爲什麼要設置內容不工作,這似乎是phantomjs API的限制。你可以使用document.write。

var phantom = require('node-phantom'); 

phantom.create(function (err, ph) { 
    return ph.createPage(function (err, page) { 
    page.open("about:blank", function(err,status) { 
     page.evaluate(function() {   
     document.write('<html><body><script>document.write("<h1>Hello From JS</h1>");</script><p>Hello from html</p></body></html>'); 
     }); 
     return page.render('./content.png', function (err) { 
     ph.exit(); 
     }); 
    }); 
    });   
}); 
+0

遺憾的是它不工作。 page.evaluate不會被執行。 – Erik 2013-04-28 20:48:39

5

JavaScript代碼需要一些時間來執行。嘗試在設置頁面內容和致電render之間有一段延遲時間。

+1

Ariya謝謝你的幻影!祝你好運與新版本:)) – Erik 2013-05-02 10:26:10

+0

感謝這個評論阿里亞,它幫助我! – JasonS 2014-05-19 02:03:11

+0

你能否檢查一下https://stackoverflow.com/questions/44602309/making-a-proper-image-capture-of-screen-using-jquery – 2017-06-18 11:07:38

0

as ariya提到,需要時間。這個庫可能有一個'onLoadFinished'事件(我使用的是節點lib)。你可以看到在這個問題的GitHub的底部我的例子處理這個沒有一個任意等待時間:https://github.com/amir20/phantomjs-node/issues/68

Document.prototype.captureScreenshot = function(next) { 
console.log(">> Rendering screencap for " + this.id) 
var self = this; 
phantom.create(function(ph) { 
    ph.createPage(function(page) { 
     page.setContent(self.html); 
     page.set("viewportSize", { 
      width: 1920, 
      height: 1080 
     }); 
     page.set('onLoadFinished', function(success) { 
      var outputFile = './screenshots/screenshot-' + self.id + '.png'; 
      page.render(outputFile); 
      ph.exit(); 
      console.log(">> Render complete for " + self.id) 
      if (next) 
       next(outputFile); 
     }) 
    }); 
}); 

}