您看到的问题是因为您没有等待页面加载,因为某些元素是异步加载的。您可以像这样等待静态时间:
var page = require('webpage').create();
page.viewportSize = { width: 650, height: 480 };
page.open('http://www5b.wolframalpha.com/input/?i=planes+overhead+90210', function (status) {
setTimeout(function() {
var clipRect = page.evaluate(function(){
return document.querySelector('#Input').getBoundingClientRect();
});
var clipRectResult = page.evaluate(function(){
return document.querySelector('#Result').getBoundingClientRect();
});
page.clipRect = {
top: clipRect.top,
left: clipRect.left,
width: clipRect.width,
height: clipRect.height + clipRectResult.height
};
console.log(JSON.stringify(clipRect));
page.render('flightsoverhead.png');
phantom.exit();
}, 5000);
});
或者您可以使用waitFor() 等待元素加载
function waitFor(testFx, onReady, timeOutMillis) {
var maxtimeOutMillis = timeOutMillis ? timeOutMillis : 3000, //< Default Max Timout is 3s
start = new Date().getTime(),
condition = false,
interval = setInterval(function() {
if ( (new Date().getTime() - start < maxtimeOutMillis) && !condition ) {
// If not time-out yet and condition not yet fulfilled
condition = (typeof(testFx) === "string" ? eval(testFx) : testFx()); //< defensive code
} else {
if(!condition) {
// If condition still not fulfilled (timeout but condition is 'false')
console.log("'waitFor()' timeout");
phantom.exit(1);
} else {
// Condition fulfilled (timeout and/or condition is 'true')
console.log("'waitFor()' finished in " + (new Date().getTime() - start) + "ms.");
typeof(onReady) === "string" ? eval(onReady) : onReady(); //< Do what it's supposed to do once the condition is fulfilled
clearInterval(interval); //< Stop this interval
}
}
}, 250); //< repeat check every 250ms
};
var page = require('webpage').create();
page.viewportSize = { width: 650, height: 480 };
page.open('http://www5b.wolframalpha.com/input/?i=planes+overhead+90210', function (status) {
var clipRect;
waitFor(function _check() {
clipRect = page.evaluate(function(){
return {
input: document.querySelector('#Input').getBoundingClientRect(),
result: document.querySelector('#Result').getBoundingClientRect(),
};
});
return clipRect && clipRect.input && clipRect.input.height > 50 && clipRect.result && clipRect.result.height > 50;
}, function _onReady(){
page.clipRect = {
top: clipRect.input.top,
left: clipRect.input.left,
width: clipRect.input.width,
height: clipRect.input.height + clipRect.result.height
};
page.render('flightsoverhead2.png');
phantom.exit();
}, 10000);
});
当您查看标记时:
<section id="answers">
<section id="Input">...</section>
<section id="Result">...</section>
<section id="SkyMap:FlightData">...</section>
</section>
您对#Input 和#Result 感兴趣,因此使用:first-child 是不够的(顺便说一下,#answers:first-child 选择了一个#answers 元素,它本身就是第一个孩子,您想使用#answers > :first-child)。您可以将所需的两个元素的尺寸与正确的clipRect 结合起来。