幻节点没有从 page.evaluate 函数传递 return 值

phantom-node not passing return value from page.evaluate function

我正在尝试提取网页的特定元素,并将其保存为本地图像。

node.js 代码,使用幻象节点:

var phantom = require('phantom');

phantom.create().then(function(ph) {

  ph.createPage().then(function(page) {

    page.property('viewportSize', {width: 1600, height: 900});
    page.open(' {

        if (status == 'success') {
            page.evaluate(function() {
                return document.getElementById("sidebar").getBoundingClientRect(); 

            }).then(function(rect){
                console.log(rect);
                page.property('clipRect', rect);
                page.render("question2.png"); 
            });   
        }
        page.close();
        ph.exit();
    });
  });
});

console.log(rect) 每次我 运行 打印不同的值。我不明白为什么会这样,但不管怎样,我想我的侧边栏边界矩形的 return 语句不起作用。代码有问题吗?

编辑:实际上,经过进一步调试,似乎 rect 被正确 returned,但没有被设置为 clipRect..

问题是 page.render 调用在 page.close() 发生之前没有足够的时间完成。

这段代码解决了问题:

var phantom = require('phantom');

phantom.create().then(function(ph) {

    ph.createPage().then(function(page) {

        page.open(' {

            if (status == 'success') {
                page.evaluate(function() {
                    return document.getElementById("sidebar").getBoundingClientRect();
                }).then(function(rect){
                    page.property('clipRect', rect);
                    page.render("question.png").then(function(){
                        page.close();
                        ph.exit();
                    });
                });
            }
        });
    });
});