我正在使用 CasperJS 阅读某个网页。我想要做的是在 CasperJS 中加载一个网页。然后,等待某个 HTML 元素具有特定文本。
所以我想做的是:
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
选择器。这样它就可以监视某个 HTML 元素中的一段文本。这是否可能以及如何可能对我来说并不是很明显。
这可以在 CasperJS 中完成吗?如果可以,我该怎么做?
最佳答案
以下函数从 waitForText()
function 中提取了一些逻辑并将其与 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 表达式(使用辅助函数)。
关于javascript - 使用 CasperJS 等待元素具有特定文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32104784/