target text after br tag using cheerio

喜欢而已 提交于 2021-01-29 05:46:31

问题


I'm practicing creating an API by scraping using cheerio. I'm scraping from this fairly convoluted site: http://www.vegasinsider.com/nfl/odds/las-vegas/

I'm trying to target the text after these <br> tags within the anchor tag in this <td> element:

<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>

The code below is what i'm using to target the data I want. The problem I'm having is I don't know how to get that text after the <br> tags. I've tried .find('br') and couldn't get it to work. Here is the code:

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);
  });
});

You can see I am able to output all the text in this box to the newObj.odds value. I was trying to use something like the next line where I'm targeting that td element and loop through and break out each row into its own newObj property, newObj.oddsLine1 and newObj.oddsLine2 for example.

Hope that makes sense. Any help is greatly appreciated.


回答1:


You can't select text nodes with cheerio, you need to use js dom properties / functions:

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

Note $(css)[0] will give you the first element as a js object (rather than a cheerio object)



来源:https://stackoverflow.com/questions/56510646/target-text-after-br-tag-using-cheerio

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!