【发布时间】:2014-10-02 00:59:00
【问题描述】:
我在使用旧 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
它始终只在第一次工作,即使我分成 2 casper.then。
【问题讨论】:
-
内容是否可能仍在加载?在
then块之前添加casper.wait(5000);。当您更新到当前的 PhantomJS 1.9.7 时会发生什么。您在页面上下文中尝试了casper.getHTML或document.querySelector("...").innerHTML哪些 native casperjs 函数?页面标记可能格式不正确,PhantomJS 在解析/查询时出错。您可以尝试将 CasperJS 版本与getHTML和 Chrome 视图源版本进行比较。您甚至可以通过 W3C 验证 Casper 版本。 -
casper.getHTML 返回完全相同的内容,但在找不到而不是返回 null 时返回错误。页面上下文中的 document.querySelector("...").innerHTML 也返回与 jQuery 相同的内容。
标签: jquery html css css-selectors casperjs