用cheerio刮文本

scraping text with cheerio

本文关键字:文本 cheerio      更新时间:2023-09-26

我正试图从这个html中抓取Jung Ho Kang5,并将其放入对象中。我想排除(R)SS中的所有内容。

<td id="lineup-table-top">
  <b class="text-muted pad-left-10">5</b>
  &nbsp;&nbsp;&nbsp;Jung Ho Kang 
  <small class="text-muted">(R)</small> 
  <small class="text-muted">SS</small>
</td>
下面是我的代码:
var someObjArr = [];
$('td#lineup-table-top').each(function(i, element){
    //Get the text from cheerio.
    var text = $(this).text();
    //if undefined, create the object inside of our array.
    if(someObjArr[i] == undefined){
        someObjArr[i] = {};
    };
    //Update the salary property of our object with the text value.
    someObjArr[i].name = text;
    $('b.pad-left-10').each(function(i, element){
        //Get the text from cheerio.
        var text = $(this).text();
        //if undefined, create the object inside of our array.
        if(someObjArr[i] == undefined){
            someObjArr[i] = {};
        };
        //Update the name property of our object with the text value.
        someObjArr[i].batting = text;
    });
});

代码的确切输出如下:

{ batting: '5',
  name: '5   Jung Ho Kang (R) SS 3B' }
{ name: '5   Jung Ho Kang (R) SS' },

期望输出:

{ batting: '5',
  name: 'Jung Ho Kang' }

我不知道为什么它似乎是循环两次,我不知道如何隔离只是名称没有它有一个类/id与它相关联。

欢迎任何指导

看起来您只想删除标记中的文本节点。

https://github.com/cheeriojs/cheerio/issues/359

我不确定是否支持nodeType,但你应该先尝试使用它。(nodeType文档)

$('td#lineup-table-top').contents().each(function(i, element){
    someObjArr[i] = someObjArr[i] || {};
    // The first element in #linup-table-top is batting stats
    if ( i === 0 && $(element).hasClass('pad-left-10') ) {
        someObjArr[i].name = $(element).text().trim();
    }
    // The raw text inside of #lineup-table-top the player name
    if ( element.nodeType === 3 ) {
        someObjArr[i].name = $(element).toString().trim();
    }
});

如果不支持,您可以返回使用element.type

if ( element.type === 'text' ) {
    someObjArr[i] = someObjArr[i] || {};
    someObjArr[i].name = $(element).toString().trim();
}

我过去使用这个方法只抓取整个页面的标记中的文本。

// For each DOM element in the page
$('*').each(function(i, element) {
    // Scrape only the text nodes
    $(element).contents().each(function(i, element) {
        if (element.type === 'text') {
        }
    });
});