如何使用casperJS等待socket.io连接返回数据? [英] How can I wait for a socket.io connection to return data using casperJS?
问题描述
我正在抓取一个使用socket.io来填充一些select标签选项的页面。在评估页面之前,如何等待套接字接收数据?我正在使用 casperJS
I am scraping a page which uses socket.io to populate some select tag options. How can I wait for the socket to receive data before evaluating the page? I am using casperJS
套接字代码(由目标网站):
the socket code (loaded by the target site):
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脚本是否已加载:
I check that the socket.io script has loaded:
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)' ?
});
但是选项标签不在页面上,大概是因为我过早评估页面
But the option tags are not on the page, presumably because I am evaluating the page too soon
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描述了我猜,虽然我不喜欢它。 Casper的waitFor通过轮询工作,而在等待事件发生时这真的很愚蠢。如果你这样做会更好:
You could do something like the following as lud1977 describes I guess, although I don't like it. Casper's waitFor works by polling, while that's really stupid when waiting for an event to happen. It would be way better if you do this:
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
这篇关于如何使用casperJS等待socket.io连接返回数据?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!