5

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?

Artjom B.
  • 61,146
  • 24
  • 125
  • 222
Vivendi
  • 20,047
  • 25
  • 121
  • 196

1 Answers1

7

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).

Artjom B.
  • 61,146
  • 24
  • 125
  • 222
  • Why nest waitFor under waitForSelector? My understanding is that each adds a step to the queue, so there shouldn't be any difference between nesting them and making them sequential. – Greg Bell Jul 26 '16 at 00:19
  • @GregBell You're right, it doesn't have to be nested. – Artjom B. Jul 26 '16 at 05:22