我唯一能做的就是前面的 <td>
将始终具有相同的(并且对于文档来说是唯一的)内容:
<td>
<label>unique text<label>
</td>
<td>dynamic text</td>
我可以在浏览器控制台中使用 jQuery 轻松获取它(页面已加载 jQuery):
$("label:contains('unique text')").parent().next().text();
我已经从事这个工作有一段时间了,并尝试了我能想到的一切。
我最近的尝试是使用 casperjs 的评估和:
casper.thenEvaluate(function addID() {
$("label:contains('unique text')").parent().next().attr('id', 'uniqueID');
});
casper.then(function getText() {
var target = this.getHTML('td#uniqueID');
this.echo(target);
});
这给了我:
CasperError: No element matching selector found: td#uniqueID
为什么我的casper.thenEvaluate
函数不创建 td#uniqueID
我正在寻找的?
如果我这样做 this post's answer :
casper.then(function getText() {
this.evaluate(function addID() {
$("label:contains('unique text')").parent().next().attr('id', 'uniqueID');
});
var target = this.thenEvaluate(function returnText() {
return $('#uniqueID').text();
});
this.echo(target);
});
我得到一个[Object Casper]
这似乎正是它听起来的样子。它充满了waitForContent
, scrollTo
等等...
注意:以上代码块不正确 (as was pointed out in this answer by Artjom B.)并更改为:
casper.then(function getText() {
this.evaluate(function addID() {
$("label:contains('unique text')").parent().next().attr('id', 'uniqueID');
});
var target = this.fetchText('#uniqueID');
this.echo(target);
});
问题仍然存在。请参阅下面我的回答以了解解决方案。
最佳答案
如果您已经像链接的答案中那样尝试过,为什么不直接复制它呢?您的错误是您在 then
block 内使用 thenEvaluate
。 CasperJS 分步骤工作,您安排了一个不必要的步骤。这将创建稍后执行的另一个步骤。
将thenEvaluate
更改为evaluate
,它应该可以正常工作。当您这样做时,您可以将两者结合起来:
casper.then(function getText() {
var target = this.evaluate(function addID() {
$("label:contains('unique text')").parent().next().attr('id', 'uniqueID');
return $('#uniqueID').text();
});
this.echo(target);
});
甚至
casper.then(function getText() {
this.evaluate(function addID() {
$("label:contains('unique text')").parent().next().attr('id', 'uniqueID');
});
var target = this.fetchText(#uniqueID);
this.echo(target);
});
关于javascript - 抓取没有 id、类、属性等的动态元素内的文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23599057/