如何使用选择器过滤'each`中的cheerio对象? [英] how to filter cheerio objects in `each` with selector?

查看:211
本文介绍了如何使用选择器过滤'each`中的cheerio对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Cheerio解析一个简单的网页,如果可能的话,我正在徘徊:

I'm parsing a simple webpage using Cheerio and I was wandering if possible is follwing:

使用这种结构的html:

With a html of this structure:

<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 等中的值。对象。

Once I get all the cheerio objects which match the tr.human selector I want to be able to loop through them to map values in classes name, surname etc. to an object.

到目前为止,我实现了这个目标:

So far I achieved this:

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}
   })
});

但我想摆脱在孩子,而我想通过选择器过滤结果,如下所示:

But I want to get rid of calling to index in children, instead I would like to filter result by a selector, something like this:

var date = result.children('td.date')

但是以上结果导致以下错误:

but above results in following error:

var date = result.children('td.date')
                          ^
TypeError: result.children is not a function

我是节点和cheerio的新手,读过Cheerio的文档,但我很喜欢这个。如何使用选择器获取某些类下的值?

I'm new to node and cheerio, read the Cheerio docs, but I'm pretty stuck with this one. How could I get the values under certain classes with usage of selectors?

我必须承认我希望第一次循环遍历元素并在每次迭代中映射到对象,而不是匹配选择器然后循环,因为这可能不保证匹配结果中的元素的正确顺序(循环和过滤器在这里不可交换),或它确实?

I must admit that I want first loop through elements and inside each iteration map to object, not to match selectors and then loop as probably this doesn't guarantee proper order of elements in matched results (loop and filter is not commutative here), or it does?

推荐答案

结果是一个裸元素,不包含在cheerio中。与jQuery类似,您可能希望再次将其包装在 $()

result is a bare element, not wrapped in cheerio. Similar to jQuery, you might want to wrap it again in $()

var date = $(result).children('td.date');

这篇关于如何使用选择器过滤'each`中的cheerio对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆