page.set('content')不适用于phantomjs中的动态内容

问题描述 投票:2回答:3

我尝试使用phantomjs用node-phantom桥屏幕捕获我的页面。这是我正在尝试的:

 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);   
    });         
  });
node.js phantomjs
3个回答
5
投票

JavaScript代码需要一些时间来执行。尝试在设置页面内容和调用render之间有一个延迟。


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
投票

正如阿里亚所说,需要时间。这个库可能有一个'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);
        })
    });
});

}

© www.soinside.com 2019 - 2024. All rights reserved.