Cheerio fails to retrieve items from the specified directory

My main goal with cheerio is to scrape the titles from this IMDb ranking:

Despite following the documentation and specifying the exact HTML path for the titles, I am getting back random and confusing objects like:

  'x-attribsNamespace': [Object: null prototype] {},
    'x-attribsPrefix': [Object: null prototype] {}
  },
  '80': <ref *81> Element {
    parent: Element {
      ...
      

Code:

import * as cheerio from 'cheerio';
import axios from 'axios';
import fs from 'fs';


axios("https://www.imdb.com/chart/tvmeter/?ref_=nv_tvv_mptv").then(res => {
    const data = res.data;
    const $ = cheerio.load(data);

    var cheerioData = $('.lister-list>tr').each((i, e) => {
        const title = $(e).find('.titleColumn a').text();
        console.log(title);
    })
    console.log(cheerioData);
})

I'm struggling to figure out what's going wrong since the path seems to be correct. Can anyone offer some help?

Answer №1

To transform the Cheerio objects array into a text array, you can utilize map in combination with spread syntax, .get(), or .toArray().

For instance, employing spread and vanilla JS Array#map:

import axios from "axios";
import cheerio from "cheerio";

const url = "<Your URL>";

axios(url).then(res => {
  const $ = cheerio.load(res.data);
  const text = [...$(".lister-list > tr")].map(e =>
    $(e).find(".titleColumn a").text().trim()
  );
  console.log(text);
})

Alternatively, you can use .get() or .toArray() after executing a Cheerio .map (where the index serves as the first argument):

const text = $(".lister-list > tr").map((i, e) =>
  $(e).find(".titleColumn a").text().trim()
).get();

If you opt for .each, you have the option to .push() each text string onto a vanilla array, although this approach isn't as elegant as utilizing .map which simplifies this process:

const text = [];
$(".lister-list > tr").each((i, e) => {
  text.push($(e).find(".titleColumn a").text().trim());
});

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Developing applications using ReactJS with Typescript can sometimes lead to errors, such as the "onclick does not exist on type x

In the code snippet below, I have a method that renders a delete icon and is used in my main container. Everything functions correctly except for a small cosmetic issue related to the type any that I am struggling to identify. import React from 'reac ...

Integrating Constant Contact API into a Next.js application

I'm trying to integrate the Constant Contact API into my Next.js application. I've looked through the documentation, but it only provides examples for PHP and Java. How can I effectively use the authentication flow and create an app on the dashbo ...

Sending data to a React component from regular HTML

I have a question about implementing a method to pass custom attributes from HTML elements as props to React components. Here's an example: function someFunction(props) { return <h1>props.something</h1> } HTML: <div id="someEl ...

Instructions for sending a PNG or JPEG image in binary format from a React app to a Node.js server

I am in the process of transferring a file from a react web app to a node.js server. To begin, I have an HTML input of type file where users can upload their files. Once a user uploads a file, a post request is triggered to my Node.js server. Within my N ...

Unable to perform type casting in Typescript

I recently dived into the world of TypeScript by picking up a book titled Typescript Revealed (Published in February 2013). Chapter 2 caught my attention with a section on "Casts" featuring an intriguing example: var a : int = <int>SomeNumberAsAStri ...

Why do referees attempt to access fields directly instead of using getters and setters?

I am facing an issue with my TypeScript class implementation: class FooClass { private _Id:number=0 ; private _PrCode: number =0; public get Id(): number { return this._Id; } public set Id(id: number) { this._Idprod ...

What is the reason for encountering the error message "Property 'floatThead' does not exist on type 'JQuery<any>' when trying to use floatThead in Angular/TypeScript?

For my project, I am incorporating the third-party jQuery library called https://github.com/mkoryak/floatThead. To work with Bootstrap and jQuery, I have installed them using NPM through the command line. Additionally, I have used NPM to install floatThea ...

Having trouble with gsap.reverse() not functioning properly when using onMouseLeave event in React

I've been incorporating simple gsap animations into my React application. I have successfully triggered an animation.play() function on onMouseEnter, but for some reason, the animation.reverse() function is not functioning as expected. Here's ho ...

There are no properties shared between type 'dateStyle: string' and type 'DateTimeFormatOptions'

"typescript": "^4.0.3" Can anyone help me resolve the TypeScript error I am encountering in the code below?: components/OrderListItem.tsx const newedate = (_date) => { const options = {dateStyle: 'medium'}; //{ weekday: ...

Unable to mock ESM with unstable_mockModule

In my project, I am utilizing ESM. The transpiled .ts files are converted into .js and stored in the 'dist' directory. Here is an example of how my directory structure looks: dist/ ├─ src/ │ ├─ store/ │ │ ├─ index.js │ ├ ...

Several arrays within the filteredData (MatTableDataSource) are being utilized

Hey there, I could really use some assistance. I have this data stored in a filteredData variable within a MatTableDataSource. filteredData My goal is to display this data in two separate tables, but I'm encountering issues where nothing is being sh ...

Error in Typescript: A computed property name must be one of the types 'string', 'number', 'symbol', or 'any'

Here is the current code I am working with: interface sizes { [key: string]: Partial<CSSStyleDeclaration>[]; } export const useStyleBlocks = ( resolution = 'large', blocks = [{}] ): Partial<CSSStyleDeclaration>[] => { cons ...

How can I display an agm-polyline within a map in Angular 7?

I need assistance with adjusting the polylines on my map and dynamically setting the zoom level based on their size and position. Here is the code I am currently using: <agm-map style="height: 500px" [latitude]='selectedLatitude' [longitude ...

How to use TypeScript variables in React applications

In my current project, I am attempting to customize a Fabric JS component (Dropdown) using styled-components within a React component. The specific CSS class names are defined in a file located at office-ui-fabric-react/lib/components/Dropdown/Dropdown.sc ...

Functions outside of the render method cannot access the props or state using this.props or this.state

Just starting out with react. I've encountered an issue where a prop used in a function outside the render is coming up as undefined, and trying to use it to set a state value isn't working either. I've researched this problem and found va ...

Experiencing trouble accessing a property in TypeScript

While working on my Next.js project, I have encountered a specific issue related to selecting the Arabic language. The translation functions correctly and the text is successfully translated into Arabic. However, the layout does not switch from its default ...

Expanding User Type to Include Extra User Data Using NextAuth.js

I encountered a dilemma where I needed to include the "profile" property in my section object to cater to different user personas in my application. However, despite retrieving the logged-in user's data from the backend and storing it in the NextAuth. ...

Guide on filtering FlatList Data in react native by selecting multiple categories from an array

User Interface Image I am looking to implement a filter functionality in the FlatList data based on top categories, where the filter button allows for multiple selections. The FlatList data is stored in the HotelData array, and the categories are also re ...

Angular time-based polling with conditions

My current situation involves polling a rest API every 1 second to get a result: interval(1000) .pipe( startWith(0), switchMap(() => this.itemService.getItems(shopId)) ) .subscribe(response => { console.log(r ...

Angular - Highlight a section of a string variable

Is there a way to apply bold formatting to part of a string assigned to a variable? I attempted the following: boldTxt = 'bold' message = 'this text should be ' + this.boldTxt.toUpperCase().bold() ; However, the HTML output is: thi ...