PhantomJS导航页面和完整的工作流程

PhantomJS Navigating Pages and complete fullwork flow

本文关键字:工作流程 导航 PhantomJS      更新时间:2023-09-26

我有一个结构如下的应用程序:

login.html >>> page1.html >>> page2.html

如果不完成前面的页面,就无法进入page2.html。现在我知道我走错了路,因为我卡住了

var page = require('webpage').create();
var system = require('system');
page.onConsoleMessage = function(msg) {
    system.stderr.writeLine('console: ' + msg);
};
function open_login(){
    login_page('https://test.com/login.html');
}
function login_page(file){
    page.open(file,function(){
        page.evaluate(function(){
        var user = document.querySelector('#username');
        var password = document.querySelector('#password');
        var submit = document.querySelector('#submit');
        user.value = 'user1';
        password.value = 'pwd1';
        submit.click();
        });
        // What now? How do I ensure that the page1.html has loaded so that i can get more elements, their values and submit to proceed to page2.html
        page.render("login.png");
        window.setTimeout(function() {
           page.render("login.png");
           phantom.exit();
        }, 5000);
    });
}
open_login();

我现在的问题是,我不知道下一步该做什么,它将正确登录,但我如何用JavaScript检查click事件已成功加载page1.html ?我不能使用jquery,也不能使用casperjs。必须是phantomjs

有一个回调函数页面。onLoadFinished在每次页面加载完成时触发。你可以在回调函数中检查当前url并做相应的事情。

page.onLoadFinished = function(result) {
    var current_url = page.evaluate(function(){
        return window.location.href;
    });
    if(result == "fail") {
        console.log("Couldn't load " + current_url);
        phantom.exit(1);
    }
    if(current_url.indexOf("page1.html") !== -1){
        do_stuff();
    }
    else if(current_url.indexOf("page2.html") !== -1){
        do_other_stuff();
    }
}