Skip to content

Instantly share code, notes, and snippets.

@geopelia
Last active August 29, 2015 14:02
Show Gist options
  • Save geopelia/dfabaa65b75ae6c2c3a7 to your computer and use it in GitHub Desktop.
Save geopelia/dfabaa65b75ae6c2c3a7 to your computer and use it in GitHub Desktop.
Script para consultar el diccionario de la RAE en linea usando phantomjs
function waitFor(testFx, onReady, timeOutMillis) {
var maxtimeOutMillis = timeOutMillis ? timeOutMillis : 9000, //< Default Max Timout
start = new Date().getTime(),
condition = false,
interval = setInterval(function() {
if ( (new Date().getTime() - start < maxtimeOutMillis) && !condition ) {
// If not time-out yet and condition not yet fulfilled
condition = (typeof(testFx) === "string" ? eval(testFx) : testFx()); //< defensive code
} else {
if(!condition) {
// If condition still not fulfilled (timeout but condition is 'false')
console.log("'waitFor()' timeout");
phantom.exit(1);
} else {
// Condition fulfilled (timeout and/or condition is 'true')
// console.log("'waitFor()' finished in " + (new Date().getTime() - start) + "ms.");
typeof(onReady) === "string" ? eval(onReady) : onReady(); //< Do what it's supposed to do once the condition is fulfilled
clearInterval(interval); //< Stop this interval
}
}
}, 500); //< repeat check every 250ms
};
var system = require('system');
var page = require('webpage').create();
page.onConsoleMessage = function(msg) {
system.stderr.writeLine( 'console: ' + msg );
};
if (system.args.length < 2) {
console.log("Uso: rae.js PALABRA_BUSCAR");
phantom.exit(1);
} else {
console.log('Cargando la pagina web');
var url = 'http://buscon.rae.es/drae/srv/search?val=' + system.args[1];
// console.log(url);
page.open(url, function (status) {
if (status !== 'success') {
console.log('No se puede acceder a la red');
phantom.exit();
} else {
console.log('La pagina cargo');
waitFor(function() {
// Check in the page if a specific element is now visible
return page.evaluate(function() {
var resp = false;
var myList = document.getElementsByTagName("div");
var myErr = document.getElementsByTagName("p");
if (myList.length > 0 || myErr.length > 0) {
resp = true;
}
return resp;
});
}, function() {
var ua = page.evaluate(function() {
var msg = "";
var myList = document.getElementsByTagName("div");
var myErr = document.getElementsByTagName("p");
var myUl = document.getElementsByTagName("ul");
if (myList.length > 0 ) {
msg = myList[0].textContent;
} else if (myErr.length > 0) {
msg = myErr[0].textContent + "\n";
if (myUl.length > 0) {
var elem = myUl.item(0);
msg += elem.textContent.replace(/ *\([^)]*\) */g, "");
}
} else {
msg = "Falla app";
}
return msg;
});
console.log(ua);
phantom.exit();
});
}
});
}
@geopelia
Copy link
Author

geopelia commented Dec 3, 2014

Ahora se logean mejor los errores 😄 Lastima que ahora aparece código de google analytics al azar

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment