用cheerio刮文本
scraping text with 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') {
}
});
});
相关文章:
- 如何使用jquery在填充自动完成的值后使文本框只读
- 使用Clipboard.js复制span文本
- 使用JS如何动态更改显示的html文件中的文本背景颜色
- 用程序搜索JQuery数据表中的文本
- jQuery匹配JSON对象的部分文本
- onkeyup无法动态创建多个文本区域
- 如何在下面的ES6循环中获得前面的文本
- 将输入字段中的文本提交到我的数据库,同时将其添加到我的列表中
- 让文本输入幻灯片显示输入时的新文本输入?然后向后滑动
- 借助asp.net验证或java脚本对多个文本进行验证
- 无法在ajaxStart中更改跨度文本
- 高亮显示时编辑文本大小和颜色
- jquery中的文本框验证
- Javascript,有没有一种方法可以将数组写成没有逗号或空格的单个文本字符串
- Sails.js:同时发布文本输入和一个文件
- Cheerio:如何根据文本内容选择元素
- 使用Cheerio从页面td元素中提取文本
- 用cheerio刮文本
- 我如何在javascript中使用cheerio选择文本区域
- 如何检索所有文本,包括'非介于'在node.js上使用cheerio的html标签