当我调用以下函数时,waitForSelector
传递给“选择器”,但 assertExists
对同一个选择器失败。怎么可能?
casper.waitForSelector(selector, function() {
casper.test.assertExists(selector, sectionName + " opened up successfully.");
}, function() {
casper.test.fail(sectionName + " did not load in given time");
}, max_timeout);
Here是使用 :nth-child
选择器重现问题的完整示例。
最佳答案
这是 WebKit 的 Qt4 分支(自 2010 年起)中的一个已知错误(请参阅 #11632、#11737)。当使用 :nth-child()
或 :nth-of-type()
CSS3 选择器时会发生这种情况。第二次运行选择器时,它返回不同的结果(大部分时间是 null
)。唯一已知的解决方法是使用 XPath 表达式而不是 CSS3 选择器。此错误已在 PhantomJS 2 中修复,因为它使用 WebKit(版本 538.1)的 Qt5 分支。
这是重现 http://example.com 问题的最小脚本(修改自 here ):
var casper = require('casper').create(),
x = require('casper').selectXPath;
casper.start('http://example.com', function() {
var selector = 'p:nth-child(3) > a',
xpSelector = '//*[local-name()="p" and position()=3]/a';
var first = this.exists(selector);
var second = this.exists(selector);
if(first !== second) {
console.error('Expected First selector to equal the Second');
} else {
console.log('Passed');
}
first = this.exists(x(xpSelector));
second = this.exists(x(xpSelector));
if(first !== second) {
console.error('Expected First selector to equal the Second');
} else {
console.log('Passed');
}
}).run();
输出:
Expected First selector to equal the Second Passed
Markup is:
<div>
<h1>text</h1>
<p>text</p>
<p><a href="url">text</a></p>
</div>
XPath 表达式看起来有点笨拙,因为它直接再现了 CSS 选择器的预期行为。通常会写成//p[2]/a
。
关于javascript - waitForSelector 通过,但同一个选择器的 assertExists 失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27835506/