Wait for an element to have a specific text with CasperJS

萝らか妹 提交于 2019-12-22 08:07:10

问题


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?


回答1:


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



来源:https://stackoverflow.com/questions/32104784/wait-for-an-element-to-have-a-specific-text-with-casperjs

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!