等待元素与CasperJS一起使用特定文本 [英] Wait for an element to have a specific text with CasperJS

查看:71
本文介绍了等待元素与CasperJS一起使用特定文本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用CasperJS来阅读某个网页。我想要做的是在CasperJS中加载一个网页。然后,等待某个HTML元素有一个特定的文本。

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.

所以我喜欢这样做:

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();

所以我想使用 waitForText ,但使用 CSS 选择器。这样它就可以监视certaim HTML元素中的一段文本。这对我来说并不是很明显是否以及如何实现。

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.

这可以在CasperJS中完成吗?如果是这样,我该怎么做?

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

推荐答案

以下函数从 waitForText() function 并将其与 waitForSelector()配对:

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;
};

将此代码放在脚本的某处,并像使用任何其他CasperJS函数一样使用该函数。 text 可以是字符串或正则表达式,选择器也可以是XPath表达式(使用辅助函数)。

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

这篇关于等待元素与CasperJS一起使用特定文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆