Javascript 如何调用按钮';PhantomJS中的onClick()方法?

Javascript 如何调用按钮';PhantomJS中的onClick()方法?,javascript,phantomjs,Javascript,Phantomjs,这不是重复的。我查看了中的答案,OP说答案是调用分配给需要单击的元素的“onClick()”方法,但OP没有说明他们是如何完成的。也没有公认的答案 我正试图用PhantonJS脚本将Android应用程序自动提交到亚马逊的应用商店。到目前为止,我已经采取了以下步骤: 打开开发人员控制台URL: 登录到我的开发者帐户 点击添加新应用链接 填充第一个应用提交表单,然后调用在此元素上定义的onclick方法: 这是第四步,这是给麻烦。代码如下: function(apptitle,categ

这不是重复的。我查看了中的答案,OP说答案是调用分配给需要单击的元素的“onClick()”方法,但OP没有说明他们是如何完成的。也没有公认的答案

我正试图用PhantonJS脚本将Android应用程序自动提交到亚马逊的应用商店。到目前为止,我已经采取了以下步骤:

  • 打开开发人员控制台URL:
  • 登录到我的开发者帐户
  • 点击添加新应用链接
  • 填充第一个应用提交表单,然后调用在此元素上定义的onclick方法:

  • 这是第四步,这是给麻烦。代码如下:

        function(apptitle,category){
                page.evaluate(function(apptitle,category){
                        document.getElementById('title').value=apptitle;
                        var sel = document.querySelector('select');
                        sel.selectedIndex = 16;
                        sanitizeManifestURL();
                },apptitle,category);
                page.render('step4.png');
                console.log(page.content);
        },
    
    我使用console.log()转储生成的HTML,它相当长,因此我创建了这个粘贴库:

    这是我生成的屏幕截图

    另一件我应该注意的事情是,我可以通过Chrome浏览器的开发者控制台让按钮工作

    更新1:

    谢谢Igor,但我仍然无法点击按钮。以下是整个脚本:

    //
    //  Run this script like so:
    //
    //       phantomjs --cookies-file=cookys.txt example_amazon_login.js 'myemailaddress@gmail.com' 'mypasswordshhhh'
    //
    //       You may need to execute the script twice so that the cookys.txt file gets data written to it.
    //       See https://stackoverflow.com/questions/41391254/not-able-to-get-phantomjs-example-to-work
    //
    
    
    var steps=[];
    var testindex = 0;
    var loadInProgress = false;//This is set to true when a page is still loading
    
    /*********SETTINGS*********************/
    var username = 'unknown';
    var password = 'unknown';
    var apptitle = 'unknown';
    var category = 'Music & Audio';
    
    var webPage = require('webpage');
    var page = webPage.create();
    
    /*
    page.onResourceRequested = function(request) {
      console.log('Request ' + JSON.stringify(request, undefined, 4));
    };
    page.onResourceReceived = function(response) {
     console.log('Receive ' + JSON.stringify(response, undefined, 4));
    };
    */
    
    page.onError = function(msg, trace) {
    
      var msgStack = ['ERROR: ' + msg];
    
      if (trace && trace.length) {
        msgStack.push('TRACE:');
        trace.forEach(function(t) {
          msgStack.push(' -> ' + t.file + ': ' + t.line + (t.function ? ' (in function "' + t.function +'")' : ''));
        });
      }
    
      console.error(msgStack.join('\n'));
    
    };
    
    page.settings.userAgent = 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/44.0.2403.157 Safari/537.36';
    page.settings.javascriptEnabled = true;
    page.settings.loadImages = false;//Script is much faster with this field set to false
    phantom.cookiesEnabled = true;
    phantom.javascriptEnabled = true;
    /*********SETTINGS END*****************/
    
    
    /* Get command line args user password*/
    var system = require('system');
    var args = system.args;
    var initial_url = 'https://developer.amazon.com/login.html';
    
    if (args.length === 1) {
      console.log('Try to pass some arguments when invoking this script!');
    } else {
      args.forEach(function(arg, i) {
        console.log(i + ': ' + arg);
        if ( i === 1 ) { username = arg; }
        if ( i === 2 ) { password = arg; }
        if ( i === 3 ) { apptitle = arg; }
      });
    }
    
    if ( username == 'unknown' ) {
            console.log('Please specify username and password');
            phantom.exit();
    }
    if ( password == 'unknown' ) {
            console.log('Please specify username and password');
            phantom.exit();
    }
    if ( apptitle == 'unknown' ) {
            console.log('Please specify apptitle');
            phantom.exit();
    }
    
    
    console.log('All settings loaded, start with execution');
    page.onConsoleMessage = function(msg) {
        console.log(msg);
    };
    /**********DEFINE STEPS THAT FANTOM SHOULD DO***********************/
    steps = [
    
            /*
             * Step 1 - Open Amazon home page
             */
            function(){
                    console.log('Step 1 - Open Amazon home page ' + initial_url);
                    // page.open("https://developer.amazon.com/home.html", function(status) {
                    page.open( initial_url, function(status) {
                            console.log('status is '+ status );
                    });
            },
    
            /*
             * Step 2 - Populate and submit the login form
             */
            function(username,password){
                    console.log('Step 2 - Populate and submit the login form');
                    // var appActionToken = page.evaluate(function() { return $('input[name="appActionToken"]').attr('value'); });
                    // console.log( 'appActionToken is ' + appActionToken );
                    console.log( 'username is ' + username );
                    console.log( 'password is ' + password );
                    page.evaluate(function(username,password){
                            console.log( '  username is ' + username );
                            console.log( '  password is ' + password );
                            document.getElementById("ap_email").value=username;
                            document.getElementById("ap_password").value=password;
                            document.getElementById("ap_signin_form").submit();
                    },username, password);
            },
            /*
             * Step 3 Click the add_new_app button
             */
            function(){
                    console.log('Step 3 - Click on the add_new_app button');
                    page.evaluate(function(){
                            var evnt = document.createEvent("MouseEvents");
                            evnt.initEvent("click",true,true);
                            document.getElementById("add_new_app_link").dispatchEvent(evnt);
    
                    });
                    //page.render('step3.png');
            },
    
            /*
             * Step 4 - Populate and submit the First App submission vorm
             *
             * <input id="submit_button" type="submit" class="button large primary one-click-submit" name="save" value="Save" onclick="sanitizeManifestURL()">
             *
             * try looking here:
             * https://stackoverflow.com/questions/32771609/how-to-click-on-selectbox-options-using-phantomjs
             *
             */
    
            function(apptitle,category,click){
                    console.log('Step 4 - save app ' + apptitle);
                    page.evaluate(function(apptitle,category,click){
                            document.getElementById('title').value=apptitle;
                            var sel = document.querySelector('select');
                            sel.selectedIndex = 16;
                            // this works
                            var evt = document.createEvent("HTMLEvents");
                            evt.initEvent("change", false, true);
                            sel.dispatchEvent(evt);
    
                            //The form will be submitted, by click on the button:
                            click('#submit_button');
                    },apptitle,category,click);
    
    //              setTimeout(function(){
                            page.render('step4.png');
    //                      console.log(page.content);
    //              },200);
            }
    ];
    
    /**********END STEPS THAT FANTOM SHOULD DO***********************/
    
    //Execute steps one by one
    interval = setInterval(executeRequestsStepByStep,50);
    function click(sel){
            var event=document.createEvent('MouseEvents');
            event.initMouseEvent('click',1,1,window,1,0,0,0,0,0,0,0,0,0,null);
            document.querySelector(sel).dispatchEvent(event);
    }
    
    function executeRequestsStepByStep(){
        if (loadInProgress == false && typeof steps[testindex] == "function") {
            console.log("testindex is " + testindex );
            if ( testindex == 1 ) {
                    console.log( "username is " + username );
                    steps[testindex](username, password);
            } else if ( testindex == 3 ) {
                    steps[testindex](apptitle, category, click);
            } else {
                steps[testindex]();
            }
            testindex++;
        }
        if (typeof steps[testindex] != "function") {
            console.log("test complete!");
            phantom.exit();
        }
    }
    
    /**
     * These listeners are very important in order to phantom work properly.
     * Using these listeners, we control loadInProgress marker which controls, weather a page is fully loaded.
     * Without this, we will get content of the page, even a page is not fully loaded.
     */
    page.onLoadStarted = function() {
        loadInProgress = true;
        console.log('Loading started');
    };
    page.onLoadFinished = function() {
        loadInProgress = false;
        console.log('Loading finished');
    };
    page.onConsoleMessage = function(msg) {
        console.log(msg);
    };
    
    //
    //按如下方式运行此脚本:
    //
    //phantomjs--cookies file=cookys.txt示例_amazon_login.js'myemailaddress@gmail.com“'MyPasswordshhh'
    //
    //您可能需要执行该脚本两次,以便cookys.txt文件获得写入其中的数据。
    //看https://stackoverflow.com/questions/41391254/not-able-to-get-phantomjs-example-to-work
    //
    var步骤=[];
    var-testindex=0;
    var loadInProgress=错误//当页面仍在加载时,此设置为true
    /*********背景*********************/
    var用户名='未知';
    var密码='未知';
    var-apptitle='未知';
    var类别=‘音乐与音频’;
    var webPage=require('webPage');
    var page=webPage.create();
    /*
    page.onResourceRequested=函数(请求){
    log('Request'+JSON.stringify(Request,未定义,4));
    };
    page.onResourceReceived=函数(响应){
    log('Receive'+JSON.stringify(response,未定义,4));
    };
    */
    page.onError=函数(消息,跟踪){
    var msgStack=['ERROR:'+msg];
    if(trace&&trace.length){
    msgStack.push('TRACE:');
    trace.forEach(函数(t){
    msgStack.push(“->”+t.file+”:“+t.line+(t.function?”(在函数“+t.function+”):”)中);
    });
    }
    console.error(msgStack.join('\n'));
    };
    page.settings.userAgent='Mozilla/5.0(windowsnt10.0;WOW64)AppleWebKit/537.36(KHTML,比如Gecko)Chrome/44.0.2403.157 Safari/537.36';
    page.settings.javascriptEnabled=true;
    page.settings.loadImages=false//将此字段设置为false时,脚本速度要快得多
    phantom.cookiesEnabled=真;
    phantom.javascriptEnabled=true;
    /*********设置结束*****************/
    /*获取命令行参数用户密码*/
    var系统=要求(“系统”);
    var args=system.args;
    变量初始值https://developer.amazon.com/login.html';
    如果(args.length==1){
    log('调用此脚本时尝试传递一些参数!');
    }否则{
    forEach(函数(arg,i){
    log(i+':'+arg);
    如果(i==1){username=arg;}
    如果(i==2){password=arg;}
    如果(i==3){apptitle=arg;}
    });
    }
    如果(用户名==“未知”){
    log('请指定用户名和密码');
    phantom.exit();
    }
    如果(密码==“未知”){
    log('请指定用户名和密码');
    phantom.exit();
    }
    如果(apptitle==“未知”){
    log('请指定apptitle');
    phantom.exit();
    }
    log('All settings loaded,start with execution');
    page.onConsolleMessage=函数(msg){
    控制台日志(msg);
    };
    /**********定义FANTOM应该执行的步骤***********************/
    步骤=[
    /*
    *步骤1-打开亚马逊主页
    */
    函数(){
    log('步骤1-打开亚马逊主页'+初始url);
    //第页打开(“https://developer.amazon.com/home.html“,功能(状态){
    页面打开(初始url、函数(状态){
    console.log('状态为'+状态);
    });
    },
    /*
    *步骤2-填写并提交登录表单
    */
    函数(用户名、密码){
    log(“步骤2-填写并提交登录表单”);
    //var appActionToken=page.evaluate(函数(){return$('input[name=“appActionToken”]')).attr('value');});
    //log('appActionToken's'+appActionToken);
    console.log('username是'+username);
    console.log('password is'+password);
    page.evaluate(函数(用户名、密码){
    console.log('username是'+username);
    console.log('password is'+password);
    document.getElementById(“ap_电子邮件”)。值=用户名;
    document.getElementById(“ap_密码”)。值=密码;
    document.getElementById(“ap签名表单”).submit();
    },用户名,密码);
    },
    /*
    *步骤3单击添加新应用程序按钮
    */
    函数(){
    log('步骤3-单击添加新应用程序按钮');
    page.evaluate(函数(){
    var evnt=document.createEvent(“MouseEvents”);
    evnt.initEvent(“单击”,真,真);
    document.getElementById(“添加新应用链接”).dispatchEvent(evnt);
    });
    //page.render('step3.png');
    },
    /*
    *步骤4-填充并提交第一个应用提交vorm
    *
    * 
    *
    *试试看这里:
    * https://stackov
    
    //
    //  Run this script like so:
    //
    //       phantomjs --cookies-file=cookys.txt example_amazon_login.js 'myemailaddress@gmail.com' 'mypasswordshhhh'
    //
    //       You may need to execute the script twice so that the cookys.txt file gets data written to it.
    //       See http://stackoverflow.com/questions/41391254/not-able-to-get-phantomjs-example-to-work
    //
    
    
    var steps=[];
    var testindex = 0;
    var loadInProgress = false;//This is set to true when a page is still loading
    
    /*********SETTINGS*********************/
    var username = 'unknown';
    var password = 'unknown';
    var apptitle = 'unknown';
    var category = 'Music & Audio';
    
    var webPage = require('webpage');
    var page = webPage.create();
    
    /*
    page.onResourceRequested = function(request) {
      console.log('Request ' + JSON.stringify(request, undefined, 4));
    };
    page.onResourceReceived = function(response) {
     console.log('Receive ' + JSON.stringify(response, undefined, 4));
    };
    */
    
    page.onError = function(msg, trace) {
    
      var msgStack = ['ERROR: ' + msg];
    
      if (trace && trace.length) {
        msgStack.push('TRACE:');
        trace.forEach(function(t) {
          msgStack.push(' -> ' + t.file + ': ' + t.line + (t.function ? ' (in function "' + t.function +'")' : ''));
        });
      }
    
      console.error(msgStack.join('\n'));
    
    };
    
    page.settings.userAgent = 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/44.0.2403.157 Safari/537.36';
    page.settings.javascriptEnabled = true;
    page.settings.loadImages = false;//Script is much faster with this field set to false
    phantom.cookiesEnabled = true;
    phantom.javascriptEnabled = true;
    /*********SETTINGS END*****************/
    
    
    /* Get command line args user password*/
    var system = require('system');
    var args = system.args;
    var initial_url = 'https://developer.amazon.com/login.html';
    
    if (args.length === 1) {
      console.log('Try to pass some arguments when invoking this script!');
    } else {
      args.forEach(function(arg, i) {
        console.log(i + ': ' + arg);
        if ( i === 1 ) { username = arg; }
        if ( i === 2 ) { password = arg; }
        if ( i === 3 ) { apptitle = arg; }
      });
    }
    
    if ( username == 'unknown' ) {
            console.log('Please specify username and password');
            phantom.exit();
    }
    if ( password == 'unknown' ) {
            console.log('Please specify username and password');
            phantom.exit();
    }
    if ( apptitle == 'unknown' ) {
            console.log('Please specify apptitle');
            phantom.exit();
    }
    
    
    console.log('All settings loaded, start with execution');
    page.onConsoleMessage = function(msg) {
        console.log(msg);
    };
    /**********DEFINE STEPS THAT FANTOM SHOULD DO***********************/
    steps = [
    
            /*
             * Step 1 - Open Amazon home page
             */
            function(){
                    console.log('Step 1 - Open Amazon home page ' + initial_url);
                    // page.open("https://developer.amazon.com/home.html", function(status) {
                    page.open( initial_url, function(status) {
                            console.log('status is '+ status );
                    });
            },
    
            /*
             * Step 2 - Populate and submit the login form
             */
            function(username,password){
                    console.log('Step 2 - Populate and submit the login form');
                    // var appActionToken = page.evaluate(function() { return $('input[name="appActionToken"]').attr('value'); });
                    // console.log( 'appActionToken is ' + appActionToken );
                    console.log( 'username is ' + username );
                    console.log( 'password is ' + password );
                    page.evaluate(function(username,password){
                            console.log( '  username is ' + username );
                            console.log( '  password is ' + password );
                            document.getElementById("ap_email").value=username;
                            document.getElementById("ap_password").value=password;
                            document.getElementById("ap_signin_form").submit();
                    },username, password);
            },
            /*
             * Step 3 Click the add_new_app button
             */
            function(){
                    console.log('Step 3 - Click on the add_new_app button');
                    page.evaluate(function(){
                            var evnt = document.createEvent("MouseEvents");
                            evnt.initEvent("click",true,true);
                            document.getElementById("add_new_app_link").dispatchEvent(evnt);
    
                    });
                    //page.render('step3.png');
            },
    
            /*
             * Step 4 - Populate and submit the First App submission vorm
             *
             * <input id="submit_button" type="submit" class="button large primary one-click-submit" name="save" value="Save" onclick="sanitizeManifestURL()">
             *
             * try looking here:
             * http://stackoverflow.com/questions/32771609/how-to-click-on-selectbox-options-using-phantomjs
             *
             */
            function(apptitle,category){
                    console.log('Step 4 - save app ' + apptitle);
                    page.evaluate(function(apptitle,category){
                            document.getElementById('title').value=apptitle;
                            // this works
                           document.querySelector('select').selectedIndex = 16;
                            $('select[lvl="1"]').change();
                            //document.querySelector('select[lvl="2"]').selectedIndex = 1;
                            //$('select[lvl="2"]').change();
    
                            //The form will be submitted, by click on the button:
                            $('#submit_button').click();
                       },apptitle,category);
    
                            page.render('step4.png');
    //                      console.log(page.content);
            },
    ];
    
    /**********END STEPS THAT FANTOM SHOULD DO***********************/
    
    //Execute steps one by one
    interval = setInterval(executeRequestsStepByStep,50);
    
    function executeRequestsStepByStep(){
        if (loadInProgress == false && typeof steps[testindex] == "function") {
            console.log("testindex is " + testindex );
            if ( testindex == 1 ) {
                    console.log( "username is " + username );
                    steps[testindex](username, password);
            } else if ( testindex == 3 ) {
                    steps[testindex](apptitle, category);
            } else {
                steps[testindex]();
            }
            testindex++;
        }
        if (typeof steps[testindex] != "function") {
      //We need to wait, after the steps is complete!
       clearInterval(interval);interval=0;
       setTimeout(function(){
       console.log("test complete!");
       page.render('complete.png');
       setTimeout(phantom.exit,2000)
       },3000);
    
        }
    }
    
    /**
     * These listeners are very important in order to phantom work properly.
     * Using these listeners, we control loadInProgress marker which controls, weather a page is fully loaded.
     * Without this, we will get content of the page, even a page is not fully loaded.
     */
    page.onLoadStarted = function() {
        loadInProgress = true;
        console.log('Loading started');
    };
    page.onLoadFinished = function() {
        loadInProgress = false;
        console.log('Loading finished');
    };
    page.onConsoleMessage = function(msg) {
        console.log(msg);
    };