使用cheerio

时间:2019-06-08 22:43:35

标签: web-scraping axios cheerio

我正在练习使用cheerio抓取来创建API。我正在从这个相当复杂的站点抓取: http://www.vegasinsider.com/nfl/odds/las-vegas/

我正在尝试在此<br>元素的定位标记内的这些<td>标记之后定位文本:

<td class="viCellBg1 cellTextNorm cellBorderL1 center_text nowrap" 
      width="56">
   <a class="cellTextNorm" href="/nfl/odds/las-vegas/line-movement/packers-@- 
       bears.cfm/date/9-05-19/time/2020#BT" target="_blank">
        &nbsp;<br>46u-10<br>-3½&nbsp;-10
   </a>
 </td>

以下代码是我用来定位所需数据的代码。我遇到的问题是我不知道如何在<br>标记后获取该文本。我尝试了.find('br'),但无法正常工作。这是代码:

app.get("/nfl", function(req, res) {
  var results = [];

  axios.get("http://www.vegasinsider.com/nfl/odds/las-vegas/").then(function(response) {
    var $ = cheerio.load(response.data);

    $('span.cellTextHot').each(function(i,element) {
      // console.log($(element).text());
      var newObj = {
        time:$(element).text()
      }
      $(element).parent().children().each(function(i,thing){
        if(i===2){
          newObj.awayTeam = $(thing).text();
        }
        else if (i===4){
          newObj.homeTeam = $(thing).text();
        }
      });
      newObj.odds= $(element).parent().next().next().text().trim();
      $('.frodds-data-tbl').find('td').next().next().children().each(function(o, oddsThing){
        if(o===0){
          newObj.oddsThing = $(oddsThing).html();
        }
      });
    res.json(results);
  });
});

您可以看到我能够将此框中的所有文本输出到newObj.odds值。我试图使用类似于下一行的内容,我将td元素作为目标并循环遍历并将其分成自己的newObj属性,例如newObj.oddsLine1和newObj.oddsLine2。

希望如此。任何帮助是极大的赞赏。

1 个答案:

答案 0 :(得分:1)

您不能选择带有cheerio的文本节点,需要使用js dom属性/函数:

$('td a br')[0].nextSibling.nodeValue

注意$(css)[0]将给您第一个元素作为js对象(而不是cheerio对象)

相关问题