본문 바로가기
Project/JavaScript

[JavaScript] 웹 스크래핑(Web Scraping) 예제(2)

by 꾸압 2022. 7. 6.

 

axios 와 cheerio 를 활용하여 인프런 사이트를 크롤링하는 예제다.

코드 작성 이전에 코드를 작성할 폴더를 열고, vscode 의 터미널에 다음을 입력한다. 

 

npm init -y

npm install axios cheerio

 


 

<코드>

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
const axios = require("axios");
const cheerio = require("cheerio");
const getHTML = async(keyword) => {
    try {
        return await axios.get("https://www.inflearn.com/courses?s=" + encodeURI(keyword));
    } catch(err) {
        console.log(err);
    }
}
const parsing = async (keyword) => {
    const html = await getHTML(keyword);
    // console.log(html); => log 를 실행하면 해당 webpage의 모든 html을 가져옴
    const $ = cheerio.load(html.data);
    const $courseList = $(".course_card_item");
    let courses = [];
    $courseList.each((idx,node) => {
        // 강의 제목 크롤링
        const title = $(node).find(".course_title").text();
        // 해당 webpage의 모든 title을 log
        // console.log(title);
        
        // 찾고자 하는 변수 혹은 class 를 기준으로 검색
        courses.push({
            title: $(node).find(".course_title:eq(0)").text(),
            instructor: $(node).find(".instructor").text(),
            price: $(node).find(".price").text(),
            rating: $(node).find(".star_solid").css("width"),
            img: $(node).find(".card-image > figure > img").attr("src")
        });
    });
    console.log(courses);
}
parsing("자바스크립트");
 
cs

 


 

<참조> https://www.youtube.com/watch?v=xbehh8lWy_A

 

 

 

 

댓글