如何使用cheerio数据抓取解析javascipt代码

问题描述

我在 youtube 上观看了视频,然后我想以不同的方式练习代码。 我想从 imdbdata 网站提取数据,然后如何解决问题 JS 代码

从 IMDB 网站获取数据

    const option = {
        uri: "https://www.imdb.com/chart/moviemeter/?ref_=nv_mv_mpm",headers: {
            Accept: "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8","Accept-Encoding": "gzip,deflate,br","Accept-Language": "en-US,en;q=0.5",},json: true,transform: (body) => cheerio.load(body),};

请求-承诺代码

    await rp(option)
        .then(($) => {
            process.stdout.write("loading...\n");
            let table = [];
            $("tbody[class='lister-list'] tr").each((i,el) => {
                //self call function
                process.stdout.write(`.`);
                let link =
                    "https://www.imdb.com" +
                    $(el).find("td[class='titleColumn'] a").attr("href");
                goToNextPage(link,table);
            });
            console.table(table);
        })
        .catch((e) => console.log(e));

我从带有参数的 request-promise JS 代码调用了 goToNextPage 函数

const goToNextPage = (link,table) => {
    let $ = cheerio.load(link);
    let title = $("div[class='title_wrapper'] > h1").text().trim(),ratingValue = $("div[class='ratingValue'] > strong > span")
            .text()
            .trim(),director = $("div[class='credit_summary_item'] > a")
            .first()
            .text()
            .trim(),filmType = $("div[class='subtext'] > a")
            .not('a[title="See more release dates"]')
            .text()
            .replace(/([A-Z])/g," $1")
            .trim();
    table.push({
        title,director,filmType,ratingValue,});
};

Why does output is only empty data showing from the console.table(table)

解决方法

您的代码通过以下方式生成点:

process.stdout.write(`.`); 

去掉那部分代码,你就没有点了。