문제

I am trying to parse html string with cheerio the problem I've got is getting index of table column

As cheerio selectors look like jQuery I tryied:

$('td:contains("Name")').index();

But it works with jQuery but with cheerio doesn't

have any of you ideas?

Edit: as you asked here is an example of html it's a quit simple table but the number of columns can be changed

<table>
   <tr>
     <td>ID</td>
     <td>Name</td>
     <td>Age</td>
   </tr>
   <tr>
      ...
   </tr>
</table>
도움이 되었습니까?

해결책 2

I don't think Cheerio implements that selector. It's similar to jQuery, but only a subset of jQuery's full implementation.

You could work around that by doing something like this:

var cheerio = require('cheerio'),
    $ = cheerio.load('<table><tr><td>ID</td><td>Name</td><td>Age</td></tr></table>');

var nameIndex = $('td').map(function(i, e) {
  if ($(this).text() === 'Name')
    return i;
})[0];

// Outputs "1" in this example.
console.log(nameIndex);

다른 팁

The version of Cheerio on github here (version 0.17.0) does in fact support .index(). The version in npm, which actually has the same version number as far as I can tell, does not.

So if you want to use index, you'll need to pull it down from github rather than through npm.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top