在nightmare.js中发送keydown,keypress类型

时间:2016-01-23 10:21:23

标签: node.js web-scraping keyboard-events electron nightmare

nightmare.js中的类型方法将文本分配给输入控件的value属性。由于这种实现keydown,按键事件不会在您试图抓取的页面上触发。在'键入'?

之后发送keydown事件的任何方法

修改1 -

这是一个使用jQuery发送事件的示例,它不起作用 -

var Nightmare = require('nightmare');
var vo = require('vo');
var nightmare = Nightmare();

vo(run)(function(err, result) {
  if (err) throw err;
});

function *run() {

  var title = yield nightmare
    .goto('http://www.cambiaresearch.com/articles/15/javascript-char-codes-key-codes')
    .type('#txtChar','\n')
    .evaluate(function() {
      var e = $.Event( "keypress", { which: 13 } );
        $('#txtChar').trigger(e);
        return "Key you pressed is : " + $('#txtChar').val();
    });

  yield  nightmare.pdf('type.pdf');
  setTimeout(function () {
    console.log( ' ' + title);
    nightmare.end();
    process.exit();
  },2000);
}

编辑2 -

使用unicode等效的键作为类型方法的参数以某种方式调用附加事件,不完全确定这个hack是如何工作的,但是它有效!

以下是工作示例 -

var Nightmare = require('nightmare');
var vo = require('vo');
var nightmare = Nightmare();

vo(run)(function(err, result) {
  if (err) throw err;
});

function *run() {

  var title = yield nightmare
    .goto('http://www.cambiaresearch.com/articles/15/javascript-char-codes-key-codes')
    .type('#txtChar','1') //so we have focus on textbox
    .type('document', '\u000d')
    .evaluate(function() {
        return "Key you pressed is : " + $('#txtChar').val();
    });

  yield  nightmare.pdf('type.pdf');
  setTimeout(function () {
    console.log( ' ' + title);
    nightmare.end();
    process.exit();
  },2000);
}

1 个答案:

答案 0 :(得分:1)

您可以使用普通的JS或jQuery来评估页面并发送keydown事件,jQuery是一种简单的方法,但它最常被注入。

使用jQuery:

.inject('js', '/jquery-2.1.4.min.js')
.evaluate(function () {
    var e = $.Event( "keypress", { which: 13 } );
    $('#yourInput').trigger(e);
});

编辑:看起来Nightmare支持触发关键事件。请查看https://github.com/segmentio/nightmare/issues/244https://github.com/segmentio/nightmare/issues/147

EDIT2:不,应该是.type('document', '\u000d')。得到了错误的unicode角色。