Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
398 views
in Technique[技术] by (71.8m points)

javascript - waitForSelector passes, but assertExists fails for the same selector

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

Here is a complete example to reproduce the issue with an :nth-child selector.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

This is a minimal script to reproduce the issue on http://example.com (modified from 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();

Output:

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>

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...