fea*_*ool 2 javascript css-selectors casperjs
我想使用CasperJS将表中的连续(内部)HTML字段提取到列表中。我知道从表中提取连续元素属性很容易,但是我不知道如何提取连续HTML字段。
为了演示,这是一个简单的HTML表:
<html>
<head></head>
<body>
<table>
<tbody>
<tr><td name="a">1</td><td>hop</td></tr>
<tr><td name="b">2</td><td>skip</td></tr>
<tr><td name="c">3</td><td>jump</td></tr>
</tbody>
</table>
</body>
</html>
Run Code Online (Sandbox Code Playgroud)
这是一个完整的Casper程序,用于从表中提取位:
"use strict";
var casper = require('casper').create();
casper.start('file:///tmp/casper-so.html');
// I want to print the list '["a", "b", "c"]'
casper.then(function a1() {
var names = casper.getElementsAttribute('table tr td[name]', 'name');
// prints ["a", "b", "c"] as desired...
console.log(JSON.stringify(names, null, 2));
});
// I want to print the list '["hop", "skip", "jump"]'
casper.then(function a2() {
var verbs = ???;
// What should go on the previous line in order to print
// ["hop", "skip", "jump"]?
console.log(JSON.stringify(verbs, null, 2));
});
casper.run();
Run Code Online (Sandbox Code Playgroud)
如代码中所述,我知道如何使用提取所有td [name]字段casper.getElementsAttribute()。但是我还没有找到从表中给定列提取内部HTML的直接方法。有指针吗?
另外:我一直在做的事情是一次提取一个元素,并使用看起来像CSS的CSS遍历索引table tr:nth-child(' + index + ') td:nth-child(2),但是感觉相当折磨。我希望找到更简单的方法。
这是一个解决方案,很大程度上是卡斯珀对getElementsAttribute()的定义所困扰:
// print the list '["hop", "skip", "jump"]'
casper.then(function a2() {
var verbs = casper.evaluate(function () {
return [].map.call(__utils__.findAll('table tr td:nth-child(2)'), function (e) { return e.innerHTML; });
});
console.log(JSON.stringify(verbs, null, 2));
});
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2207 次 |
| 最近记录: |