繁体   English   中英

在Nightmare JS中的click()和wait()之后获取POST请求标头

[英]Get POST request headers after click() and wait() in Nightmare JS

我正在抓取一个页面,在其中在输入字段中type()某些内容, click()一个按钮,然后wait()以使某些元素出现。

我想获取click()之后触发的POST请求的所有标头。

我看到goto()返回了标头,但我认为我无法使用它,因为在click()我停留在同一页面上。

这是另一个测试页上的代码示例(我想在wait()之后获取POST请求标头):

var Nightmare = require('nightmare');
var nightmare = Nightmare({ show: true });

nightmare
    .goto('https://jigsaw.w3.org/HTTP/300/')
    .click('tbody tr:nth-child(5) td form input[type=submit]')
    .wait('body p:nth-of-type(3)')
    .evaluate(function () {
        return document.querySelector('body p:nth-of-type(3)').innerText;
    })
    .end()
    .then(function (result) {
        console.log(result);
    })
    .catch(function (error) {
        console.error('Search failed:', error);
    });

注意:我使用Nightmare 2.10.0和Node.js 8.1.3。

我知道没有简单的方法可以做到这一点。

但是,您可以获取该信息。

通过.on('did-get-response-details', callback)

如果调用.on('did-get-response-details')其回调将包含以下信息:

  • event Event
  • status Boolean
  • newURL String
  • originalURL String
  • httpResponseCode Integer
  • requestMethod String
  • referrer String
  • headers Object
  • resourceType String

您必须先调用.on(<event>)然后再调用.goto()

可用事件列表位于此处: https : //electron.atom.io/docs/api/web-contents/#instance-events

通过.evaluate

您可以通过ajax直接转到POST端点(而不是通过表单提交来提交表单)。

从这里偷来的Ajax示例: 使用XMLHttpRequest发送POST数据

nightmare.evaluate(() => {
    return new Promise((resolve, reject) => {
        var http = new XMLHttpRequest();
        var url = "get_data.php";
        var params = "lorem=ipsum&name=binny";
        http.open("POST", url, true);

        http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");

        http.onreadystatechange = function() {
            if(http.readyState == 4 && http.status == 200) {
                resolve(http); // <- Get some data here
            }
        }
        http.send(params);
    });
});

这两个想法如何具体解决您的用例将取决于某些事情。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM