2016-12-29 52 views
2

我想从使用PhantomJS的简单表单中获得结果。我正在使用jQuery,但不起作用。我有这样的HTML:如何在使用PhantomJS提交表单后获得结果?

<!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(); 

    }; 


    }); 
}); 

回答

3

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火灾每次页面加载完成时,使用此实现幻像将退出加载页面的第一个页面,即使在表单之前提交。

您需要执行一些检查来区分页面的第一次和第二次加载。例如,如果返回html变量为空,这意味着我们还没有提交页面。

+3

非常感谢。我只是将它添加到你的代码中,它是否工作: if(html!=“”){console.log(html); phantom.exit();} –

相关问题