如何将此html数据表提取到csv文件。
<table id="parts" class="parts-first horizontal">
<tbody>
<tr class="odd">
<td class="score"><span class="rb">69</span</td>
<td class="score part"><span class="p1_home">31</span></td>
</tr>
<tr class="even">
<td class="score"><span class="rb">63</span></td>
<td class="score part"><span class="p1_away">17</span></td>
</tr>
</tbody>
</table>
给出这两行数据:
69
31
63
17
请注意,这些数据是可刷新的,它们每隔一分钟就会更改一次,因此我的csv文件必须包含类似的内容:
11,23
11,34
19,39
22,30
22,99
22,33
...
答案 0 :(得分:2)
如果您只是需要代码来获取数据并从中形成CSV字符串,那么您就去了。它将它输出到控制台,但您可能会使用Ajax和PHP更新实际文件。
window.addEventListener('DOMContentLoaded', init, false);
function init(){
var table = document.getElementById('parts');
var csvString = table2csv(table, ',', false);
console.log( csvString ); // Now you can save this string in a variable, or send it
}
function table2csv(table, delimitor, trailing){
var data = '',
rows = table.getElementsByTagName('tr');
for(var i=0, l=rows.length; i<l; i++){
var line = [],
cells = rows[i].getElementsByTagName('td');
for(var j=0, k=cells.length; j<k; j++){
var value = cells[j].textContent.trim(' ');
line.push(value);
}
data += line.join(delimitor) + (trailing?delimitor:'') + "\n";
}
return data + "\n\n";
}
&#13;
The CSV should appear in your console.
<table id="parts" class="parts-first horizontal">
<tbody>
<tr class="odd">
<td class="score"><span class="rb">69</span</td>
<td class="score part"><span class="p1_home">31</span></td>
</tr>
<tr class="even">
<td class="score"><span class="rb">63</span></td>
<td class="score part"><span class="p1_away">17</span></td>
</tr>
</tbody>
</table>
&#13;