如何为 HTML 结构编写 cheerio 查询?

How to write cheerio query for HTML structure?

我的 cheerio 代码片段如下。我正在尝试获取 <td> 标签中的项目名称,并获取后续 td 标签 (1,2,1) 中的数字。

itemName 查询有效,但 startPrice、endPrice 和 difPrice 查询无效。我的逻辑哪里有问题,还是句法错误?

var $ = cheerio.load(html);

//
$('.table-item-link').each(function(i, element) {
    var itemName = ($(this).attr('title');
    console.log(itemName);
});

//Iterate through all tr inside div = 'content'
$('.content tr').each(function(i, element) {
    var startPrice = $(this).children()[2].children()[0].text();
    var endPrice = $(this).children()[3].children()[0].text();
    var difPrice = $(this).children()[4].children()[0].text();
    console.log(price)
});
<div class='content'>
    <table>
        <thead>
             <tr>Table Title</tr>
             <tbody>
               <tr>
                 <td>
                   <a href="http://services.runescape.com/m=itemdb_rs/Jangerberry_seed/viewitem?obj=5104" title="Jangerberry seed" class='table-item-link'>
            <img src='http://services.runescape.com/m=itemdb_rs/5125_obj_sprite.gif?id=5104' alt="Jangerberry seed"><span>Jangerberry seed</span>
           </a>
                   </td>
                 <td class='memberItem'><img src='http://www.runescape.com/img/rs3/grand_exchange/tick.png' title="Members Only" alt="Yes" /></td>
           <td><a href="http://services.runescape.com/m=itemdb_rs/Oak_toy_box/viewitem?obj=9849">1</a></td>
           <td><a href="http://services.runescape.com/m=itemdb_rs/Oak_toy_box/viewitem?obj=9849">2</a></td>
           <td><a href="http://services.runescape.com/m=itemdb_rs/Oak_toy_box/viewitem?obj=9849">1</a></td>
             <td class='change positive'><a href="http://services.runescape.com/m=itemdb_rs/Oak_toy_box/viewitem?obj=9849">+100%</a></td>
         </tr>
               <****repeat a bunch of tr w/ same format as above****>
               <****close all other tags****************************>
           

好的,我检查了你的代码。为什么不选择 just

var arr = [];
$(".content tr a").each(function (i, elem) {
  var a = $(elem);
  var text = a.text().trim().toLowerCase();
  arr.push(text);
});

您也可以按 i 值过滤,例如 i !== 2, i !== 3