PhantomJS 并单击表单按钮

2023-04-21前端开发问题
11

本文介绍了PhantomJS 并单击表单按钮的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

我有一个非常简单的 HTML 表单,我正在尝试使用各种数据进行测试.我使用 IE 对象在 MS Access/VBA 中编写了一个原型概念验证.它运行良好,但完成的测试产品必须使用 PhantomJS.我已经让页面接口工作并且表单填充得很好.我被卡住的地方是让提交按钮触发.我已经梳理了 S.O.并尝试了所有建议,但没有任何效果.我正在使用 PhantomJS 1.9.7 并使用直接的 JavaScript 测试脚本.

I have a very simple HTML form that I'm attempting to test with various kinds of data. I wrote a prototype proof-of-concept in MS Access/VBA using the IE object. It worked fine but the finished testing product has to use PhantomJS. I've got the page-interfacing to work and the form is populating just fine. Where I'm stuck is getting the submit button to fire. I've combed through S.O. and tried all suggestions and nothing is working. I'm using PhantomJS 1.9.7 and using straight JavaScript test scripts.

我尝试了各种 JavaScript 技术来触发提交按钮.为了满足只使用 JQuery"的人群,我也尝试过.没有任何工作.当我在测试脚本结束时呈现表单时,我看到表单填充了耐心等待 <search> 的数据.按钮被点击.

I tried various JavaScript techniques to fire the submit button. To satisfy the "Just use JQuery" crowd, I tried that too. Nothing is working. When I render the form at the end of the test script, I see the form populated with data patiently waiting for the <search> button to be clicked.

以下是我尝试过的总结:

Here's a summary of what I tried:

  1. document.getElementById('btnSearch').click();
  2. $("btnSearch").click();
  3. var el = document.getElementById('btnSearch');//获取搜索按钮对象
    $(el).click();
  4. document.getElementById('Form1').submit();
  5. 尝试创建一个点击事件并从按钮对象触发它(在下面的代码中)
  6. 尝试创建一个点击事件并从 body 对象中使用相关按钮内某个点的坐标触发它
  1. document.getElementById('btnSearch').click();
  2. $("btnSearch").click();
  3. var el = document.getElementById('btnSearch'); // Get search button object
    $(el).click();
  4. document.getElementById('Form1').submit();
  5. Tried creating a click event and firing it from the button object (in the code below)
  6. Tried creating a click event and firing it from the body object with the coordinates of a point inside the button in question

表格如下:(请不要对 CSS 的缺乏、表格的使用等发表评论/辩论.我对网站的创建者没有发言权或影响力.)

Here's the form: (And please, no comments/debates on the lack of CSS, use of tables, etc. I have no say or influence over the people who created the site.)

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<HTML>
    <HEAD>
        <title>Da Site</title>
    </HEAD>
    <body>
    <form name="Form1" method="post" action="Default.aspx" id="Form1">
    <TABLE id="Table2" cellSpacing="2" cellPadding="1" border="0">
      <TR>
        <TD>Street Address:</TD>
        <TD><input name="Address" type="text" maxlength="100" id="Address" /></TD>
      </TR>
      <TR>
        <TD>City:</TD>
        <TD><input name="City" type="text" maxlength="100" id="City" style="width:232px;"/></TD>
      </TR>
      <TR>
        <TD>State:</TD>
        <TD><select name="State" id="State">
                    <option value=""></option>
                    <option value="AL">AL - Alabama</option>
                    <option value="AK">AK - Alaska</option>
                    [The rest of the other states]
                    <option value="WI">WI - Wisconsin</option>
                    <option value="WY">WY - Wyoming</option>
                    <option value="PR">PR - Puerto Rico</option>
            </select>
        </TD>
      </TR>
      <TR>
        <TD>Zip Code:</TD>
        <TD><input name="ZipCode" type="text" maxlength="5" id="ZipCode" /></TD>
      </TR>
      <tr>
        <td><input type="submit" name="btnSearch" value="Search" id="btnSearch" />
            <input type="submit" name="btnReset" value="Reset" id="btnReset" />
        </td>
      </tr>
    </TABLE>
    </form>
    </body>
</HTML>

这是驱动表单的 JavaScript:

Here's the JavaScript to drive the form:

var maxtimeOutMillis = 3000;
var start;
var finish;

var page = require('webpage').create();

// Route "console.log()" calls from within the Page context to the main Phantom context (i.e. current "this")
page.onConsoleMessage = function(msg) {
                                      console.log(msg);
                                      };

page.open('http://www.MadeUpURL.com/', function(status) {

  page.includeJs("http://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js", function() {

  if (status !== 'success') {
    console.log('Unable to access network');
  } else {
         page.render('before.png');  // Renders the blank form
         page.evaluate(
              function () {
                          // page.render('Sample.png');
                          document.getElementById('Address').value = '123 Somewhere Drive';
                          document.getElementById('City').value = 'Somewhere';
                          document.getElementById('State').selectedIndex = 36;
                          document.getElementById('ZipCode').value = '12345';

         // I've done a page.render() here and it shows the form fully and correctly populated

                          // Now let's submit the form...
                          var el = document.getElementById('btnSearch');   // Get the "search" button object

                          // Tried the usual suspects
                          document.getElementById('btnSearch').click();
                          $("btnSearch").click();
                          $(el).click();
                          document.getElementById('Form1').submit();

                          // Tried creating a click event and firing it from the button object
                          var ev = document.createEvent("MouseEvent");
                          ev.initMouseEvent("click",
                                            true /* bubble */,
                                            true /* cancelable */,
                                            window,
                                            null,
                                            0, 0, 0, 0, /* coordinates */
                                            false, false, false, false, /* modifier keys */
                                            0 /*left click*/,
                                            null);
                          el.dispatchEvent(ev);

                          // Tried calculating the location of the button itself (which works) and fire the click event from the <Body> object
                          var obj = document.getElementById('btnSearch');
                          var x = obj.offsetLeft;
                          var y = obj.offsetTop;

                          while (obj.offsetParent) {
                            x = x + obj.offsetParent.offsetLeft;
                            y = y + obj.offsetParent.offsetTop;
                            if (obj == document.getElementsByTagName("body")[0])
                              {
                                break;
                              }
                              else
                              {
                                obj = obj.offsetParent;
                              }
                            }

                          x = x + 5; // Tried with and without this +5 delta
                          y = y + 5; // Tried with and without this +5 delta

                          console.log('X = ' + x);
                          console.log('Y = ' + y);

                          var ev = document.createEvent("MouseEvent");
                          ev.initMouseEvent("click",
                                            true /* bubble */,
                                            true /* cancelable */,
                                            window,
                                            null,
                                            0, 0, x, y, /* coordinates */
                                            false, false, false, false, /* modifier keys */
                                            0 /*left click*/,
                                            null);
                          document.body.dispatchEvent(ev);

                          });
         start = new Date().getTime();
         finish = new Date().getTime();
         console.log('Time before: ' + start);
         // Check to see if results are defined (or times out)
         while ( (finish - start < maxtimeOutMillis) &&  !( page.evaluate( function() {return document.getElementById('TheAnswer');})))
           {
           finish = new Date().getTime();
           }
         console.log('Time after: ' + finish);
         if ( page.evaluate( function() {return document.getElementById('TheAnswer');}))
           {
           console.log(page.evaluate( function() {return document.getElementById('TheAnswer').textContent;}));
           }
         else
           {
           console.log('Element not defined');
           }
         }
  page.render('after.png');
  phantom.exit();

  });

});

我希望这是一种你忘记分号的东西,但我就是没看到.任何帮助将不胜感激!

I'm hoping this is one of those you-forgot-a-semicolon kind of things, but I just don't see it. Any help would be very much appreciated!

编辑#1:添加脚本输出以供参考.

Edit #1: Adding the script output for reference.

C:TempWebAutomationPhantomJSscripts>phantomjs interact.js
X = 151
Y = 442
Time before: 1407875912197   [edit #2 - change before/after labels to match code]
Time after: 1407875915197
Element not defined
C:TempWebAutomationPhantomJSscripts>

推荐答案

好的.我想我想通了.我将 PhantomJS 和我的脚本定向到一个网站,在那里我可以监控后端的数据.令我惊讶的是,按钮 被点击了.我只是看不到结果.

Ok. I think I figured it out. I directed PhantomJS and my script to a website where I could monitor the data on the back-end. To my surprise, the button was being clicked. I just couldn't see the results.

感谢 这篇博文来自 Vinjay Boyapati,问题似乎更多地与页面处理程序和排序有关.似乎在 PhantomJS 中处理页面转换的最佳方法是启动页面循环(单击提交按钮、链接等)并退出 JS 评估功能.在检查 PhantomJS 以确保页面已完全加载且稳定后,调用另一个 page.evaluate 并在浏览器取回提交结果时查找您希望找到的任何内容.这是我从 Vinjay 的帖子中复制/修改的代码:

Courtesy of this post from Vinjay Boyapati, the problem appears to have more to do with page handlers and sequencing. It seems that the best way to handle page transitions in PhantomJS is to initiate the page cycle (click on a submit button, a link, etc.) and exit that JS evaluate function. After checking PhantomJS to make sure the page had completely loaded and was stable, call another page.evaluate and look for whatever you expected to find when the browser fetched back the results of your submission. Here's the code that I copied/modified from Vinjay's post:

编辑:需要特别注意的一件事.对于需要 jQuery 的每个 page.Evaluates(),我添加了 page.injectJs("jquery1-11-1min.js"); 行.否则我会得到$ is undefined"作为页面错误.

Edit: One thing to draw particular attention to. For each page.Evaluates() where jQuery is needed, I'm adding the page.injectJs("jquery1-11-1min.js"); line. Otherwise I would get "$ is undefined" as a page error.

var page = require('webpage').create();
var loadInProgress = false;
var testindex = 0;

// Route "console.log()" calls from within the Page context to the main Phantom context (i.e. current "this")
page.onConsoleMessage = function(msg) {
    console.log(msg);
};

page.onAlert = function(msg) {
    console.log('alert!!> ' + msg);
};

page.onLoadStarted = function() {
    loadInProgress = true;
    console.log("load started");
};

page.onLoadFinished = function(status) {
    loadInProgress = false;
    if (status !== 'success') {
        console.log('Unable to access network');
        phantom.exit();
    } else {
        console.log("load finished");
    }
};

var steps = [
    function() {
        page.open('http://www.MadeUpURL.com');
    },

    function() {
        page.injectJs("jquery1-11-1min.js");
        page.evaluate(function() {
            document.getElementById('Address').value = '302 E Buchtel Avenue'; //University of Akron if you're wondering
            document.getElementById('City').value = 'Akron';
            document.getElementById('State').selectedIndex = 36;
            document.getElementById('ZipCode').value = '44325';
            console.log('JQ: ' + $().jquery);
            $('#btnSearch').click();
            console.log('Clicked');
        });
    },
    function() {
        console.log('Answers:');
        page.injectJs("jquery1-11-1min.js");
        page.render('AnswerPage.png');
        page.evaluate(function() {
            console.log('The Answer: ' + document.getElementById('TheAnswer').innerHTML);
            $('#buttonOnAnswerPage').click(); // This isn't really necessary unless you need to navigate deeper
            console.log('Sub button clicked');
        });
    },
    function() {
        console.log('More Answers:'); // This function is for navigating deeper than the first-level form submission
        page.render('MoreAnswersPage.png');
        page.evaluate(function() {
            console.log('More Stuff: ' + document.body.innerHTML);
        });
    },
    function() {
        console.log('Exiting');
    }
];

interval = setInterval(function() {
    if (!loadInProgress && typeof steps[testindex] == "function") {
        console.log("step " + (testindex + 1));
        steps[testindex]();
        testindex++;
    }
    if (typeof steps[testindex] != "function") {
        console.log("test complete!");
        phantom.exit();
    }
}, 50);

这篇关于PhantomJS 并单击表单按钮的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

The End

相关推荐

js删除数组中指定元素的5种方法
在JavaScript中,我们有多种方法可以删除数组中的指定元素。以下给出了5种常见的方法并提供了相应的代码示例: 1.使用splice()方法: let array = [0, 1, 2, 3, 4, 5];let index = array.indexOf(2);if (index -1) { array.splice(index, 1);}// array = [0,...
2024-11-22 前端开发问题
182

layui中表单会自动刷新的问题
layui中表单会自动刷新的问题,因为用到layui的表单,遇到了刷新的问题所以记录一下: script layui.use(['jquery','form','layer'], function(){ var $ = layui.jquery, layer=layui.layer, form = layui.form; form.on('submit(tijiao)', function(data){ a...
2024-10-23 前端开发问题
262

JavaScript小数运算出现多位的解决办法
在开发JS过程中,会经常遇到两个小数相运算的情况,但是运算结果却与预期不同,调试一下发现计算结果竟然有那么长一串尾巴。如下图所示: 产生原因: JavaScript对小数运算会先转成二进制,运算完毕再转回十进制,过程中会有丢失,不过不是所有的小数间运算会...
2024-10-18 前端开发问题
301

jQuery怎么动态向页面添加代码?
append() 方法在被选元素的结尾(仍然在内部)插入指定内容。 语法: $(selector).append( content ) var creatPrintList = function(data){ var innerHtml = ""; for(var i =0;i data.length;i++){ innerHtml +="li class='contentLi'"; innerHtml +="a href...
2024-10-18 前端开发问题
125

JavaScript(js)文件字符串中丢失"\"斜线的解决方法
问题描述: 在javascript中引用js代码,然后导致反斜杠丢失,发现字符串中的所有\信息丢失。比如在js中引用input type=text onkeyup=value=value.replace(/[^\d]/g,) ,结果导致正则表达式中的\丢失。 问题原因: 该字符串含有\,javascript对字符串进行了转...
2024-10-17 前端开发问题
437

layui中table列表 增加属性 edit="date",不生效怎么办?
如果你想在 layui 的 table 列表中增加 edit=date 属性但不生效,可能是以下问题导致的: 1. 缺少日期组件的初始化 如果想在表格中使用日期组件,需要在页面中引入 layui 的日期组件,并初始化: script type="text/javascript" src="/layui/layui.js"/scrip...
2024-06-11 前端开发问题
455