编程语言
首页 > 编程语言> > javascript-如何等待使用casperJS的socket.io连接返回数据?

javascript-如何等待使用casperJS的socket.io连接返回数据?

作者:互联网

我正在抓取一个页面,该页面使用socket.io填充一些选择标记选项.在评估页面之前,如何等待套接字接收数据?我正在使用casperJS

套接字代码(由目标站点加载):

socket.on('list', function (data) {


$.each(data.match_names, function (id, name) {
    if (some condition) {
        /*nothing*/
    } else {
        if (typeof( varname ) == 'function') {
            $('#myselector').append('<option value="' + id + '">' + name + " " + get_tournament_name(id.substr(0, 4)) + '</option>');
        } else {
            $('#myselector').append('<option value="' + id + '">' + name + '</option>');
        }
        match_count++;
    }
});

我检查socket.io脚本是否已加载:

casper.waitForResource("socket.io.js", function() {
    this.echo('socket.io has been loaded.'); //is printed

//how can I check that data has arrived from 'socket.on('list', function (data)' ?
});

但是选项标签不在页面上,大概是因为我评估页面太早了

casper.then(function() {
    baseTargetUrl = this.evaluate(function() {
        return __utils__.getElementByXPath('//*[@id="wrapper"]/div[1]/a[2]')["href"];
    });
    console.log('logging: '+baseTargetUrl); // works

    casper.thenOpenAndEvaluate(baseTargetUrl ,function() { //baseTargetUrl is no longer undefined, it's a closure now

        $(function(){ // DOM is ready

            var myOptions = [] ;

            $('select#myselector option').each(function(){
                myOptions.push( $(this).text() + ' : '+$(this).val() ); //additional options have not yet been added

            });

        });
    });
});

解决方法:

尽管我不喜欢lud1977所描述的,但您可以执行以下操作.卡斯珀的waitFor通过轮询来工作,而在等待事件发生时这确实很愚蠢.如果这样做,那就更好了:

var list = null; // broader scope

casper.on('socket.list', function() {
  // do stuff with <list> here
});

casper.waitForResource("socket.io.js", function() { 
  var socket = io.connect("http://wherever-the-server-is")
  socket.on('list', function(data){
    list = data;
    this.emit('socket.list');
  }.bind(this));
})

来源:http://docs.casperjs.org/en/latest/events-filters.html

标签:javascript,casperjs
来源: https://codeday.me/bug/20191010/1883152.html