问题
I am currently able to scroll down a page with the help of CasperJS. I saw this article on how to scroll infinite pages based on the visibility of certain attributes. However I don't want to base it on the visibility of an element but was wondering if there is a way to set a timer on how long it should stay scrolling down before exiting out. How would be able to such thing?
//function to scroll
function tryAndScroll(casper) {
casper.page.scrollPosition = {
top: casper.page.scrollPosition["top"] + 40000,
left: 0
};
}
/**
* Everything starts here!
* I use the mobile version of facebook as the DOM is waaay simpler to scrape.
*/
casper.start('https://www.somesite.com', function() {
});
casper.then(function() {
tryAndScroll(this);
});
casper.then(function() {;
this.exit();
});
casper.run();
回答1:
Here's a simple way:
function tryAndScroll(casper) {
casper.page.scrollPosition = {
top: casper.page.scrollPosition["top"] + 300,
left: 0
};
}
casper.start(url).then(function() {
var self = this;
var intervalId = setInterval(function(){
tryAndScroll(self);
}, 100); // retry interval
self.wait(10000 /* infinite scroll timeout */, function(){
clearInterval(intervalId);
});
}).run();
Since setInterval()
is not a CasperJS step function, this essentially break out of the control flow of CasperJS. The wait()
is necessary so that CasperJS doesn't execute something else during the scroll.
Also, you can't use a scroll distance of 40000 pixels. This is too big and PhantomJS won't be able to take a screenshot.
来源:https://stackoverflow.com/questions/32531266/scroll-down-page-event-for-x-seconds