티스토리 뷰

반응형


.Install cheerio module

- Install Cheerio from npm  npm i cheerio 


.Using 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
const request = require("request");
const cheerio = require("cheerio");
 
scrapingResult = {
    'date''',
    'the_basic_rate''',
    'buy''',
    'sell'''
}
 
function getData() {
    request("https://finance.naver.com/marketindex/exchangeDailyQuote.nhn"function (err, res, body) {
        const $ = cheerio.load(body);
        const bodyList = $(".tbl_exchange tbody tr").map(function (i, element) {
            scrapingResult['date'= String($(element).find('td:nth-of-type(1)').text());
            scrapingResult['the_basic_rate'=  String($(element).find('td:nth-of-type(2)').text());
            scrapingResult['buy'=  String($(element).find('td:nth-of-type(4)').text());
            scrapingResult['sell'=  String($(element).find('td:nth-of-type(5)').text());
 
            console.log(scrapingResult)
        });
    });
}
 
getData();
cs


line 2) cheerio module 불러오기

line 12~22) 크롤링하고자하는 page 를 request 해준다.

line 13) body 내용을 저장


line 14) 일별 시세 정보가 나와있는 태그를 찾아야 한다.

     찾고자하는 일별 시세 테이블의 정보는 tbl_exchange > tobody > tr 태그 안에 있다.

일별 시세를 모두 뽑아오기 위해 map 함수를 사용


line 15~18) 일별 시세 테이블의 정보를 찾았으니, 필요한 데이터만 뽑아줘야 한다.

$(element).find('td:nth-of-type(n)').text()

코드 그대로 element 에서 td:nth-of-type(N) N 번째 요소의 text() 값을 가져오는 것이다.



결과는 아래와 같이 나오게 된다.



반응형
댓글
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday