刮与cheerio的文本
我正在试图从这个html中刮掉Jung Ho Kang
和5
,并把它放到一个对象中。 我想排除(R)
和SS
。
<td id="lineup-table-top"> <b class="text-muted pad-left-10">5</b> 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') { } }); });