I am using CheerioJS to scrape a list of text from a site. I am correctly finding the text, however something strange is happening when using .each on an array of table rows.
Here is my code
const getTopCollections = async () => {
const response = await axios.get('https://www.nft-stats.com/top-collections/7d')
const $ = cheerio.load(response.data)
const return_data = []
const table = $('table').children('tbody')
table.each((i, element) => {
let col_name = $(element).find('a').text()
return_data.push(col_name)
})
console.log(return_data);
return return_data
What I am getting is instead of an array of strings in return_data, I am getting one large string with all of the text in one string, like below:
I'm guessing it is something to do with how CheerioJS returns data from .each()? I tried saving the result of each .find().text() into its own variable and then inserting that but that didn't fix it.
As I said in the comments, Cheerio is a weird clone of jQuery and doesn't behave exactly like it. $(element).find('a')
finds all the <a>
but returns one single Cheerio object. You can iterate the links with
$(element).find('a').each( ..... push etc )
or
$(element).find('a').toArray().forEach( element => ... )