Node.js

[Next.js] 멜론 차트 크롤링하기

이경욱 2024. 1. 11. 18:30
    const getHtml = async () => {
        const cheerio = require('cheerio')
        const chartInfo = new Array();
        const title: string[] = [];
        const artist: string[] = [];
        console.log('getHTML')
        try {
            const html = await axios.get('https://www.melon.com/chart/');
            const $ = cheerio.load(html.data)
            $('.ellipsis.rank01 > span > a').each((idx : number, el : any) => {
                const titleInfo = el.children[0].data;
                title[idx] = titleInfo;
            });
            $('.checkEllipsis').each(function (this: any, idx: number) {
                const artistInfo = $(this).text();
                artist[idx] = artistInfo;
            });
            for (let i = 0; i < title.length; i++) {
                chartInfo[i] = {'Rank' : i+1, 'Title' : title[i], 'Artist' : artist[i]}
            }
            return chartInfo;

        } catch (err) {
            console.error('axios error', axios)
            console.error(err)
        }
    }

 

 

axios와 cheerio를 통해 html을 파싱한 후

특정 태그 안으로 들어가 text() 메서드를 이용해 원하는 값을 받아왔다.

그리고 객체 배열을 만들어서 return 하였다.