【问题标题】:How to get results after submit form with PhantomJS?使用 PhantomJS 提交表单后如何获得结果?
【发布时间】:2016-12-29 03:36:40
【问题描述】:

我正在尝试使用 PhantomJS 从一个简单的表单中获取结果。我正在使用 jQuery 但不起作用。我有这个 HTML:

<!doctype html>
<html>
<head>
    <title>PhantomJS!</title>
</head>
<body>
<form method="post" id="frm">
<input type="text" name="nombre" id="nombre" />
<input type="submit" value="Publicar" id="btn-submit" />
</form>

Your name is <span id="nombrez"><?php if (isset($_POST['nombre'])) { echo $_POST['nombre'];} ?></span>

</body>
</html>

还有这段 Javascript 代码:

var page = require('webpage').create();
page.open('http://localhost/phantom/', function() {
  page.includeJs("https://code.jquery.com/jquery-3.1.1.slim.js", function() {
    page.evaluate(function() {

      $('#nombre').val('Fabian');
    document.forms[0].submit();
   });

    page.onLoadFinished = function(){

    console.log($("#nombrez").html());
    phantom.exit();

    };  


  });
});

【问题讨论】:

    标签: phantomjs


    【解决方案1】:

    page.onLoadFinished 不能在 page.evaluate 内部调用,而是在 PhantomJS 主脚本内部调用:

    var page = require('webpage').create();
    
    page.onLoadFinished = function(){
    
        var html = page.evaluate(function(){
            return document.getElementById("nombrez").innerHTML;
        });
        console.log(html);
        phantom.exit();
    
    };  
    
    page.open('http://localhost/phantom/', function() {
        page.includeJs("https://code.jquery.com/jquery-3.1.1.slim.js", function() {
            page.evaluate(function() {
    
            $('#nombre').val('Fabian');
                document.forms[0].submit();
            });
        });
    });
    

    但是,page.onLoadFinished 会在每次页面加载完成时触发,并且使用此实现,幻影将在页面加载的第一次退出,甚至在表单提交之前。

    您需要执行一些检查来区分页面的第一次和第二次加载。例如,如果 return html 变量为空,则表示我们还没有提交页面。

    【讨论】:

    • 非常感谢。我刚刚将它添加到您的代码中并且它是否有效:if(html != "") {console.log(html);phantom.exit();}
    猜你喜欢
    • 2013-05-17
    • 2015-04-14
    • 2012-03-04
    • 1970-01-01
    • 2016-09-11
    • 1970-01-01
    • 1970-01-01
    • 2020-02-11
    • 1970-01-01
    相关资源
    最近更新 更多