带有jQuery和CSS3选择器的CasperJS没有按预期工作



在一些使用旧HTML的页面中选择元素时遇到一些问题。

如果我在Chrome javascript控制台中注入jQuery并自己执行代码,它会返回正确的值。然而,当我尝试在CasperJS中这样做时,它不起作用。所以我制作了一个小脚本来测试正在发生的事情:

(已提交casper.start和casper.run)

casper.then(function() {
    this.echo("1: Entire Row");
    this.echo(this.evaluate(function() {
        return $("#table20 > tbody > tr:nth-child(3)").html();
    }));
    this.echo("2: More specific");
    this.echo(this.evaluate(function() {
        return $("#table20 > tbody > tr:nth-child(3) > td:nth-child(2)").html();
    }));
    this.echo("3: More specific");
    this.echo(this.evaluate(function() {
        return $("#table20 > tbody > tr:nth-child(3) > td:nth-child(2) > p").html();
    }));
    this.echo("4: Even more specific");
    this.echo(this.evaluate(function() {
        return $("#table20 > tbody > tr:nth-child(3) > td:nth-child(2) > p > font").html();
    }));
    this.echo("5: Using jQuery functions");
    this.echo(this.evaluate(function() {
        return $("#table20 > tbody > tr:nth-child(3)").children("td:nth-child(2)").children("p").children("font").html();
    })); //Ugly workaround
});

当我运行它时,结果是:

1: Entire Row
<td height="23" width="226" style="border-style: solid; border-width: 1px" bordercolor="#666666" colspan="2">
        <p>
        <img width="16px" height="16px" src="upload/imagens/bandeira_eua.gif">
        <strong>Dólar americano (USD)</strong>
</p></td>
<td height="23" width="80" style="border-style: solid; border-width: 1px" bordercolor="#666666">
        <p><font size="2">2,400</font>
</p></td>
<td height="23" width="81" style="border-style: solid; border-width: 1px" bordercolor="#666666">
        <p><font size="2">2,600</font>
</p></td>
2: More specific //Correct so far...
<p><font size="2">2,400</font> 
</p>
3: More specific //What? This is from another row!!
<font size="2">3,060</font>
4: Even more specific
null //What??
5: Using jQuery functions
2,400 //Correct result

然而,如果我使用Chrome访问网站,并在控制台中注入相同的jQuery,那么它会按预期运行:

$("#table20 > tbody > tr:nth-child(3) > td:nth-child(2) > p > font").html();
"2,400"

发生了什么事???使用本机的CasperJS方法来检索值也不起作用。

ps:CasperJS版本1.1.0-beta3与PhantomJS版本1.9.0

ps1:CSS路径是在Chrome开发工具"复制CSS路径"中生成的。

编辑:更奇怪的是:这个脚本

casper.then(function() {
    this.echo(this.evaluate(function() {
        return $("#table20 > tbody > tr:nth-child(3) > td:nth-child(2) > p > font").html();
    }));
    this.echo(this.evaluate(function() {
        return $("#table20 > tbody > tr:nth-child(3) > td:nth-child(2) > p > font").html();
    }));
});

退货:

2,400
null

它始终只在第一次工作,即使我分成两个casper.then。

不幸的是,Casper/PhantomJS Webkit与chrome的不同。Xpath在chrome上的工作并不总是在PhantomJS上工作,要找到原因,需要深入研究复杂的C++代码。

基本上,这并不能回答问题,但证实了我以前也遇到过同样的情况。解决方法是找到一个更一致的向下钻取的xpath,通过文本、属性、类、id等来定位元素……而不是从那里向下钻取。即使你必须经过你的元素才能工作,它也会一直到父母或兄弟姐妹等等…这比基于通用标签的绝对dom路径更可靠。

在phantomjs中,诸如//div/div/p/a/span/text()之类的xpath不是很可靠。

最新更新