MorningSleeper
MorningSleeper

Reputation: 415

Extract all values between spans

If there were two occurrences of tbody on a page, how could I extract all the values between the spans in the 2nd occurrence of tbody which is below? The id's (id=id1, id=id2, etc) only appear once in the entire document, in the 2nd tbody.

<tbody>
    <tr>
        <td><b>
            <span id="id1">1,209</span></b></td>
        <td><b>
            <span id="id2">$&nbsp;14.6381</span></b><br />
            (<span id="id3">16:26:20 PM</span>)</td>
        <td><b>
            <span id="id4">$&nbsp;14.55</span></b><br />
            (<span id="id5">19:58:12 PM</span>)</td>
    </tr>
</tbody>

So far I have the following

var $ = cheerio.load(html);
$('tbody').each(function(i, element) {
if(i == 1){
var children = $(this).children();
}
});

Upvotes: 0

Views: 743

Answers (1)

matt
matt

Reputation: 1753

See the below code. I'm using jquery but cheerio should be the same commands.

//var $ = cheerio.load(html);
$(function() {

  var idsFromSpans = [];
  $('tbody')
    .first() //Grab the first tbody
    .next() //Grab the second tbody
    .find('span') //Grab all span elements
    .each(function(i, element) {
      idsFromSpans.push($(element).text()); //Grab contents of span
    });

  console.log(idsFromSpans);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
  <tbody>
  </tbody>
  
  <tbody>
    <tr>
      <td><b>
        <span id="id1">1,209</span></b></td>
      <td><b>
        <span id="id2">$&nbsp;14.6381</span></b><br />
        (<span id="id3">16:26:20 PM</span>)</td>
      <td><b>
        <span id="id4">$&nbsp;14.55</span></b><br />
        (<span id="id5">19:58:12 PM</span>)</td>
    </tr>
  </tbody>
</table>

Upvotes: 2

Related Questions