skip to Main Content

After scraping a page , I have selected the footer of a table using cheerio with:

const $ = cheerio.load(data);
const foot = $('#tblAcctBal > tfoot > tr');
o = $(foot).html();
console.log(o);

results in the following html:

tr> <th rowspan="1" colspan="1"></th>
<th rowspan="1" colspan="1"></th>
<th rowspan="1" colspan="1"></th>
<th rowspan="1" colspan="1"></th>
<th rowspan="1" colspan="1"></th>
<th rowspan="1" colspan="1">$0.00</th>
<th rowspan="1" colspan="1">$0.00</th>
<th rowspan="1" colspan="1">$0.00</th>
<th rowspan="1" colspan="1">$0.00</th>
<th rowspan="1" colspan="1">$0.00</th>undefined</tr>n

I’m trying to get an array of the text values in the footer. I’ve tried:

$(foot).each( function (th) {
    console.log($(th).text().trim())
  })

but I’m getting no output. How do I fix this?

2

Answers


  1. Select the th elements and loop over those.

    const feet = $('#tblAcctBal > tfoot > tr > th');
    
    for (const el of feet){
      console.log($(el).text())
    }
    
    const values = feet
      .map((i, el) => $(el).text())
      .toArray()
    
    console.log(values)
    

    As a side note, .each() and other iterating functions in cheerio supply both the index and element in the function signature.

    feet.each((index, el) => {
      console.log(index, $(el).text())
    })
    

    In the example code, the selector returns a single tr element, which would need something like .children() to get each th element.

    const row = $('#tblAcctBal > tfoot > tr')
    console.log(row.length) // 1
    $(row).children().each((i, el) => {
      console.log(i, $(el).text())
    })
    
    Login or Signup to reply.
  2. if they’re really there you can just do:

    $('tfoot tr th').get().map(el => $(el).text())
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search