问题描述
当我调用以下函数时,waitForSelector 为选择器"传递,但 assertExists 对同一选择器失败.怎么可能?
When I call the following function, waitForSelector passes for 'selector', but assertExists fails for the same selector. How is it possible?
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);
这里是使用 :nth-child 重现问题的完整示例 选择器.
推荐答案
这是一个已知的错误(参见 #11632,#11737)在 WebKit 的 Qt4 分支中(来自2010).当使用 :nth-child() 或 :nth-of-type() CSS3 选择器时会发生这种情况.选择器第二次运行时,它返回不同的结果(大部分时间是 null).唯一已知的解决方法是使用 XPath 表达式而不是 CSS3 选择器.此错误已在 PhantomJS 2 中修复,因为它使用 WebKit 的 Qt5 分支(版本 538.1).
This is a known bug (see #11632, #11737) in the Qt4 fork of WebKit (from 2010). It happens when :nth-child() or :nth-of-type() CSS3 selectors are used. The second time the selector is run, it returns a different result (most of the time null). The only known workaround is to use XPath expressions instead of CSS3 selectors. This bug is fixed in PhantomJS 2 as it uses a Qt5 fork of WebKit (version 538.1).
这是在 http://www.51sjk.com/Upload/Articles/1/0/332/332230_20221020143705415.com 上重现问题的最小脚本(修改自 这里):
This is a minimal script to reproduce the issue on http://www.51sjk.com/Upload/Articles/1/0/332/332230_20221020143705415.com (modified from here):
var casper = require('casper').create(), x = require('casper').selectXPath; casper.start('http://www.51sjk.com/Upload/Articles/1/0/332/332230_20221020143705415.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();
输出:
标记是:
Markup is:
<div> <h1>text</h1> <p>text</p> <p><a href="url">text</a></p> </div>
XPath 表达式看起来有点尴尬,因为它直接再现了 CSS 选择器的预期行为.通常人们会写 //p[2]/a.
The XPath expression looks a little awkward, because it directly reproduces the intended behavior of the CSS selector. Normally one would write //p[2]/a.