node.js - 在 Nightmare.js 中发送 keydown、keypress 类型

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

nightmare.js 中的 Type 方法将文本分配给输入控件的 value 属性。由于此实现 keydown,keypress 事件不会在您尝试抓取的页面上触发。有什么方法可以在“输入”后发送 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 作为类型方法的参数会以某种方式调用附加事件,不完全确定这个黑客是如何工作的,但它确实有效!

这是工作示例-

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);
}

最佳答案

您可以使用纯 JS 或 jQuery 评估页面并发送 keydown 事件,jQuery 是最简单的方法,但它最需要注入(inject)。

使用 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 .

编辑2:不,应该是.type('document', '\u000d')。得到了错误的 unicode 字符。

关于node.js - 在 Nightmare.js 中发送 keydown、keypress 类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34962253/

相关文章:

c++ - 重复时禁用按键事件

Python bind - 允许同时按下多个键

node.js - 如何自动测试 Node 中的内存泄漏?

javascript - 为什么不在Phaser中上传图像?

VBA:如何在 <td> 标签中获取隐藏的href

python - 单击登录按钮后 Ebay 网站挂起 - Selenium Python

Python 抓取维基百科表然后导出到 csv

JavaScript - 跨浏览器检测 ESC 键

node.js - 简单的 nodemon.json 配置来监视除某些文件之外的所有文件

javascript - 哈希德 : ReferenceError: require is not defined