web-crawler - 如何使用Nightmarejs(或casperjs/phantomjs)遵循自动表单提交和重定向

标签 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>

此页面的script元素提交表单。并发送对http://somewhere/的发布请求。然后http://somewhere/返回302对http://another/的响应。

为了获取最后一页(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选项。

最佳答案

您可以使用.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)方法。在此处查看文档:https://github.com/segmentio/nightmare

关于web-crawler - 如何使用Nightmarejs(或casperjs/phantomjs)遵循自动表单提交和重定向,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26591732/

相关文章:

javascript - Highcharts 导出为 svg

node.js - 如何使用nightmare.js页面事件

javascript - 如何使用node.js获取没有ID的元素 Nightmare

Java CSS 爬虫

web-crawler - DokuWiki 下载器

Ruby 网络蜘蛛和搜索引擎库

javascript - 使用 phantomjs 在单击时加载 javascript/ajax 调用

javascript - 为什么 Phantom.js 在处理 JavaScript 后没有从我的 HTML 中删除它?

amazon-web-services - Glue爬虫如何加载Redshift表中的数据?

javascript - 单击链接后让 Nightmare 等待下一页加载