简体   繁体   English

发送keydown事件在PhantomJS中不起作用

[英]Sending the keydown event does not work in PhantomJS

I tried this code with a web page which its content loaded dynamically when we press keydown. 我在一个网页上尝试了此代码,当我们按下按键时会动态加载其内容。 (like facebook) (如facebook)

The goal is to get all net traffic and print it to console. 目标是获取所有净流量并将其打印到控制台。

var page = require('webpage').create(),
    system = require('system'),
    address;

if (system.args.length === 1) {
    console.log('Usage: netlog.js <some URL>');
    phantom.exit(1);
} else {
    address = system.args[1];

    page.onLoadFinished      = function(req) {
        console.log('requested: ' + JSON.stiringify(req, undefined, 4));

    };
    page.open(url, function () {
        page.sendEvent('keypress', page.event.key.keydown); 
    });
    page.onResourceRequested = function (req) {
        console.log('requested: ' + JSON.stringify(req, undefined, 4));
    };

    page.onResourceReceived = function (res) {
        console.log('received: ' + JSON.stringify(res, undefined, 4));
    };


    page.open(address, function (status) {
        if (status !== 'success') {
            console.log('FAIL to load the address');
        }
        phantom.exit();
    });

}

First of all, PhantomJS is asynchronous. 首先,PhantomJS是异步的。 You're opening two pages at the same time. 您同时打开两个页面。 When the second page.open() the loading of the first page is aborted. 当第二个page.open()时,第一页的加载被中止。 This means that your page.sendEvent() call is never executed. 这意味着您的page.sendEvent()调用将永远不会执行。

If you want to see whether the event is doing something, you need to let the page load and after doing some action wait a little to see if there are requests: 如果要查看事件是否正在执行某些操作,则需要让页面加载,并在执行一些操作后稍等一下是否有请求:

if (system.args.length === 1) {
    console.log('Usage: netlog.js <some URL>');
    phantom.exit(1);
} else {
    address = system.args[1];

    page.onResourceRequested = function (req) {
        console.log('requested: ' + JSON.stringify(req, undefined, 4));
    };

    page.onResourceReceived = function (res) {
        console.log('received: ' + JSON.stringify(res, undefined, 4));
    };


    page.open(address, function (status) {
        if (status !== 'success') {
            console.log('FAIL to load the address');
            phantom.exit(1);
        }

        page.sendEvent('keypress', page.event.key.keydown); 

        setTimeout(function(){
            phantom.exit();
        }, 1000);
    });
}

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

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