如何使用nightmarejs(或casperjs / phantomjs)跟踪自动表单提交和重定向

时间:2014-10-27 16:02:42

标签: web-crawler phantomjs nightmare

使用nightmarejs,我想跟随几个重定向和自动表单提交,这是由页面脚本调用的。并希望获得最后一页。

例如,http://myexample/的页面内容如下:

<html><body>
<form action="http://somewhere/" method="post">
  <!-- some params -->
</form>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script>
$('form').submit();
</script>
</body></html>

此页面的脚本元素提交表单。并且发送了对http://somewhere/的发布请求。然后http://somewhere/会向http://another/返回302回复。

要获取最后一页(http://another/),我尝试了这样的nightmarejs代码:

var Nightmare = require('nightmare');
new Nightmare()
    .goto('http://myexample/')
    .wait(1000)
    .url(function(url) {
        console.log(url);
    })
    .evaluate(function () {
        return window.location.href;
    }, function (res) {
        console.log(res);
    })
    .run();

我尝试了urlevaluate方法,但我无法获得最后一页。

有没有办法支持这样的情况?使用casperjs或phantomjs的答案也是受欢迎的。

更新

我尝试了PhanomJS并且能够遵循重定向。但是还存在另一个问题,即SSL Handshake failed错误导致连接失败。我已解决此问题以添加--ssl-protocol=any选项。

2 个答案:

答案 0 :(得分:2)

您可以使用.wait(fn [,arg1,arg2,...])方法进行重定向。

var loginUrl = '...';
var loggedInUrl = '...';
new Nightmare().goto(loginUrl)
  .type('#username', '')
  .type('#password', '')
  .click('#loginBtn')
  .wait(function () {
    return window.location.href === loggedInUrl;
  });

或者,如果目标URL上有一些唯一的DOM元素,则可以使用.wait(selector)方法。在这里查看文档:{​​{3}}

答案 1 :(得分:0)

您可以使用API​​中描述的事件来检查重定向何时发生。如果您使用urlchanged事件,则会获得可以使用的新网址。

https://github.com/segmentio/nightmare#onevent-callback