gpt4 book ai didi

javascript - 用 cheerio 抓取文本

转载 作者:行者123 更新时间:2023-11-30 07:59:26 25 4
gpt4 key购买 nike

我试图从这个 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 的情况下仅隔离名称。

任何方向都受到热烈的赞赏。

最佳答案

看起来您只想抓取标记中的文本 Node 。

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

我不确定 nodeType 是否受支持,但您应该先尝试使用它。 ( nodeType docs )

$('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') {

}
});
});

关于javascript - 用 cheerio 抓取文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31949521/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com