【问题标题】:Sending keydown, keypress on type in nightmare.js发送 keydown,在 nightmare.js 中键入 keypress
【发布时间】:2016-01-23 10:21:22
【问题描述】:

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 等效的键作为参数来键入方法会以某种方式调用附加事件,不完全确定这个 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);
}

【问题讨论】:

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


    【解决方案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 字符。

    【讨论】:

    • 感谢您的回复。我尝试了您建议的两个选项,但都不适合我,请查看我在上面添加的示例,它实现了您的建议。
    • 我已经更新了答案,我使用了错误的 unicode 字符。
    猜你喜欢
    • 2011-11-17
    • 2011-03-23
    • 2022-01-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多