Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Wait for an element to have a specific text with CasperJS

I'm using CasperJS to read a certain web page. What I want to do is load a web page in CasperJS. Then, wait for a certain HTML element to have a specific text.

So what I'd LIKE to do is this:

var casper = require('casper').create();

casper.start('http://www.example.com/somepage', function() {
    this.echo('Home page opened');
});

// wait for text based on a CSS selector
casper.waitForText('.someCssClass', 'dolor sit', function() {
    this.echo('found title!');
});

// when text is eventually found, then continue with this
casper.then(function() { ... } );

casper.run();

So I'd like to use waitForText, but with a CSS selector. So that it can monitor a piece of text in a certaim HTML element. It's not really obvious to me if and how this is possible.

Can this be done in CasperJS? If so, how can I do that?

like image 478
Vivendi Avatar asked Aug 19 '15 20:08

Vivendi


1 Answers

The following function takes a bit of logic from the waitForText() function and pairs it with waitForSelector():

var utils = require("utils");
casper.waitForSelectorText = function(selector, text, then, onTimeout, timeout){
    this.waitForSelector(selector, function _then(){
        this.waitFor(function _check(){
            var content = this.fetchText(selector);
            if (utils.isRegExp(text)) {
                return text.test(content);
            }
            return content.indexOf(text) !== -1;
        }, then, onTimeout, timeout);
    }, onTimeout, timeout);
    return this;
};

Put this code somewhere at the begging of your script and use the function just like any other CasperJS function. text can be a string or regular expression and the selector can also be a XPath expression (using the helper function).

like image 177
Artjom B. Avatar answered Nov 09 '22 13:11

Artjom B.