首页 > 解决方案 > 使用java脚本从html表中提取元素

问题描述

<tbody class='detail' onclick='singleDelayCall(toggleDetail, event, this)'><tr><td Class='cluster' rowspan='539'>core</td>
<td Class='name' rowspan='539'>bilateral_1t_throttle0</td>
<td Class='result-name '>timing: cycles</td>
<td Class='metric' title='Test gave a performance metric.' lastPassTag=''>31787.0</td>
<td Class='metric' title='Test gave a performance metric.' lastPassTag=''>4967.0</td>
<td Class='metric' title='Test gave a performance metric.' lastPassTag=''>33695.0</td>
<td Class='metric' title='Test gave a performance metric.' lastPassTag=''>4967.0</td>
</tr><tr class='detail-hide'><td Class='result-name '>pmu: COUNTER0_OVERFLOW</td>
<td Class='' title='' lastPassTag=''>&nbsp;</td>
<td Class='metric' title='Test gave a performance metric.' lastPassTag=''>0.0</td>
<td Class='' title='' lastPassTag=''>&nbsp;</td>
<td Class='metric' title='Test gave a performance metric.' lastPassTag=''>0.0</td>
</tr><tr class='detail-hide'><td Class='result-name '>pmu: COUNTER2_OVERFLOW</td>
<td Class='' title='' lastPassTag=''>&nbsp;</td>
<td Class='metric' title='Test gave a performance metric.' lastPassTag=''>0.0</td>
<td Class='' title='' lastPassTag=''>&nbsp;</td>
<td Class='metric' title='Test gave a performance metric.' lastPassTag=''>0.0</td>
</tr><tr class='detail-hide'><td Class='result-name '>pmu: COMMITTED_PKT_ANY</td>
<td Class='metric' title='Test gave a performance metric.' lastPassTag=''>1997.0</td>
<td Class='metric' title='Test gave a performance metric.' lastPassTag=''>1997.0</td>
<td Class='metric' title='Test gave a performance metric.' lastPassTag=''>1997.0</td>
<td Class='metric' title='Test gave a performance metric.' lastPassTag=''>1997.0</td>

我想只提取 31787.0,4967.0,33695.0,4967.0 属于 merit class 的数字。它们是<tr> class='cluster'</tr>. 我不想要那些在优点但不低于的数字<tr> class='cluster'</tr>。我试过这个,但它不起作用

var list = document.getElementsByClassName('cluster')[0];
zlen=list.getElementsByClassName('metric')[0].innerHTML; 
for (var i = 0; i <=10; i++) {
      z = zlen[i].innerHTML;
      document.writeln(z);

任何修改或建议表示赞赏。谢谢

标签: javascripthtmlweb-scraping

解决方案


您只选择了metric类的第一个元素!您需要更改的内容:

var list = document.getElementsByClassName('cluster')[0];
zlen=list.getElementsByClassName('metric'); 
for (var i = 0; i <=10; i++) {
      z = zlen[i].innerHTML;
      document.writeln(z);

编辑:我为你做了一个小提琴JSFiddle

请注意:

  • 我已经Class改为class

  • 并将 a 更改class='cluster'tdatr


推荐阅读