我正在使用 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()功能 https://github.com/n1k0/casperjs/blob/1.1-beta3/modules/casper.js#L2211-L2222并将其与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 表达式(使用辅助函数)。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)