The CasperJS documentation has a pretty good description of what it does casper.evaluate().
Recall: you pass a function that will be executed in the context of the DOM (you can also call it the context of the page). You can pass some primitives as arguments to this function and return one primitive back. Keep in mind that this function that you pass on evaluatemust be autonomous. It cannot use variables or functions defined outside this function.
CasperJS provides many good features for everyday tasks, but you may run into a situation where you need a custom function for something. evaluatemostly there
- Retrieve some value from the page to take action based on this in the script
- Manipulate the page in any way other than clicking or filling out the form
- Combinations of points 1. and 2.
Examples
, checked . CasperJS getElementAttribute, .
function getChecked(cssSelector){
return document.querySelector(cssSelector).checked;
}
if (casper.evaluate(getChecked, selector)){
} else {
}
, . data-uid li, 2 uids.
Casper-:
var uids = casper.getElementsAttribute('ul#user-list > li', 'data-uid');
Casper-:
var uids = casper.evaluate(function(){
return Array.prototype.map.call(document.querySelectorAll('ul#user-list > li'), function(li){ return li["data-uid"]});
});
, , . , -, , . CSS .
:
function removeSelector(cssSelector){
var elements = document.querySelectorAll(cssSelector);
Array.prototype.forEach.call(elements, function(el){
el.parent.removeChild(el);
});
}
casper.evaluate(removeSelector, '.ad');
CSS:
function applyCSS(yourCss){
var style = document.createElement("style");
style.innerHTML = yourCss;
document.head.appendChild(style);
}
casper.evaluate(applyCSS, 'body { background-color: black; }');
CasperJS PhantomJS , , . PhantomJS page.evaluate() :
. evaluate . : JSON, .
, , DOM .. !