如何使用选择器过滤`each`中的cheerio对象?
how to filter cheerio objects in `each` with selector?
我正在使用 Cheerio 解析一个简单的网页,如果可能的话,我正在徘徊:
有一个html这个结构:
<tr class="human">
<td class="event"><a>event1</a></td>
<td class="name">name1</td>
<td class="surname"><a>surname1</a></td>
<td class="date">2011</td>
</tr>
<tr class="human">
<td class="event"><a>event2</a></td>
<td class="name">name2</td>
<td class="surname"><a>surname2</a></td>
<td class="date">2012</td>
</tr>
<tr class="human">
<td class="event"><a>event3</a></td>
<td class="name">name3</td>
<td class="surname"><a>surname3</a></td>
<td class="date">2013</td>
</tr>
一旦我得到所有与 tr.human
选择器匹配的 cheerio 对象,我希望能够遍历它们以映射 类 name
、surname
中的值等到一个对象。
到目前为止我实现了这个:
var cheerio = require('cheerio');
var fs = require('fs')
fs.readFile('./humans.html', 'utf8', function (err,data) {
if (err) {
return console.log(err);
}
const $ = cheerio.load(data)
var results = $('tr.human')
results.each(function(i, result){
var date = result.children[3]
var name = result.children[1]
var surname = result.children[2]
var object = {"name":name,"date":date,"surname":surname}
})
});
但我想摆脱在 children
中调用索引,而是想通过选择器过滤 result
,如下所示:
var date = result.children('td.date')
但以上导致以下错误:
var date = result.children('td.date')
^
TypeError: result.children is not a function
我是 node 和 cheerio 的新手,请阅读 Cheerio 文档,但我对这个很感兴趣。如何使用选择器获取某些 类 下的值?
我必须承认我希望 first 遍历元素并在每次迭代中映射到对象,而不是匹配选择器然后循环,因为这可能不能保证正确的顺序匹配结果中的元素(循环和过滤器在这里不可交换),还是可以?
result
是一个裸元素,没有包裹在 cheerio 中。与 jQuery 类似,您可能希望将其再次包裹在 $()
中
var date = $(result).children('td.date');
我正在使用 Cheerio 解析一个简单的网页,如果可能的话,我正在徘徊:
有一个html这个结构:
<tr class="human">
<td class="event"><a>event1</a></td>
<td class="name">name1</td>
<td class="surname"><a>surname1</a></td>
<td class="date">2011</td>
</tr>
<tr class="human">
<td class="event"><a>event2</a></td>
<td class="name">name2</td>
<td class="surname"><a>surname2</a></td>
<td class="date">2012</td>
</tr>
<tr class="human">
<td class="event"><a>event3</a></td>
<td class="name">name3</td>
<td class="surname"><a>surname3</a></td>
<td class="date">2013</td>
</tr>
一旦我得到所有与 tr.human
选择器匹配的 cheerio 对象,我希望能够遍历它们以映射 类 name
、surname
中的值等到一个对象。
到目前为止我实现了这个:
var cheerio = require('cheerio');
var fs = require('fs')
fs.readFile('./humans.html', 'utf8', function (err,data) {
if (err) {
return console.log(err);
}
const $ = cheerio.load(data)
var results = $('tr.human')
results.each(function(i, result){
var date = result.children[3]
var name = result.children[1]
var surname = result.children[2]
var object = {"name":name,"date":date,"surname":surname}
})
});
但我想摆脱在 children
中调用索引,而是想通过选择器过滤 result
,如下所示:
var date = result.children('td.date')
但以上导致以下错误:
var date = result.children('td.date')
^
TypeError: result.children is not a function
我是 node 和 cheerio 的新手,请阅读 Cheerio 文档,但我对这个很感兴趣。如何使用选择器获取某些 类 下的值?
我必须承认我希望 first 遍历元素并在每次迭代中映射到对象,而不是匹配选择器然后循环,因为这可能不能保证正确的顺序匹配结果中的元素(循环和过滤器在这里不可交换),还是可以?
result
是一个裸元素,没有包裹在 cheerio 中。与 jQuery 类似,您可能希望将其再次包裹在 $()
var date = $(result).children('td.date');