Apify Discord Mirror

Updated 5 months ago

How to create a new cheerio instance $?

At a glance

The community member is trying to instantiate a new Cheerio object to select a specific element for further processing. The current code uses cheerioModule.load(spec) to create a new Cheerio instance for each element, but the community member is unsure if this is the right approach.

In the comments, another community member suggests that the community member does not need to use load() and can instead use the $ instance provided by Crawlee to select the specific element: const elem = $(spec); This will return a Cheerio object scoped only to the spec element.

The comments provide an answer to the community member's question on how to create a new Cheerio instance using the $ provided by Crawlee.

I need to instatiate a new cheerio object, i'm doing a search in a set o elements and need to select just one element for further processing, my actual code is:
Plain Text
function getOrigin($: typeof cheerioModule) {
    let origin = ""
    const specElements = $('#product_specs table tr').toArray()
    for (const spec of specElements) {
        const _$ = cheerioModule.load(spec)
        const specTitle = _$(".attrib").text().trim()
        if(specTitle.includes("์ œ์กฐ๊ตญ")){
            origin = _$(".attrib-val").text().trim()
            break
        }
    }
    return origin
}

but i'm not sure if that is the right way to instantiate a new cheeio object in crawlee.
e
t
2 comments
How to create a new cheerio instance $?
You don't need to use load(). Instead of doing this:
Plain Text
const _$ = cheerioModule.load(spec);


Just do this using the $ already provided to you by Crawlee:
Plain Text
const elem = $(spec);


It will return a Cheerio object scoped only to that spec element. ๐Ÿ˜„
Add a reply
Sign up and join the conversation on Discord