如何使用PhantomJS连续多次访问页面? [英] How to visit a page several times in a row with PhantomJS?

查看:126
本文介绍了如何使用PhantomJS连续多次访问页面?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以打开页面,做我的事情并关闭它。超时后再次访问它以查看内容更改(页面有许多js函数)。试图连续两次打开页面使PhantomJS表现不可预测。那么解决方案是什么?

Is it possible to open page, do my things and close it. And after a timeout visit it once again to see the content changes (page has many js functions). Trying to open the page twice in a row makes PhantomJS behave unpredictable. What is the solution then?

推荐答案

PhantomJS中的大多数执行都是异步的,所以你必须在第一次之后打开一个页面页面加载完成:

Most the execution in PhantomJS is asynchronous, so you have to open a page only after the first page load was completed:

page.open(url, function(){
    setTimeout(function(){
        // do something
        page.open(url, function(){
            setTimeout(function(){
                // do something
                phantom.exit();
            }, 5000); // 5 seconds
        });
    }, 5000); // 5 seconds
});

甚至更好地使用递归:

var i = 0;
function run(){
    if (i > 100) { // stop execution at some point
        phantom.exit();
    }
    page.open(url, function(){
        // do what you have to do
        setTimeout(run, 5000); // run again in 5 seconds
    });
}
run();

这篇关于如何使用PhantomJS连续多次访问页面?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆