오픈그래프 태그 스크래핑 실습

SSAD·2023년 2월 15일
0

스크래핑 실습

cheerio - html 파싱 라이브러리

공식 사이트
npm
Fast, flexible, and lean implementation of core jQuery designed specifically for the server

  • jQuery를 서버사이드에 맞게 수정한 것
  • jQuery와 유사하게 동작하므로 기존에 사용하던 사람은 좀더 편안하게 사용

실습 환경 구축

mkdir folder
cd folder

touch index.js

// type module 추가 
yarn init

yarn add axios
yarn add cheerio

index.js

import axios from 'axios';
import cheerio from 'cheerio';

async function createBoardAPI(mydata) {
  // 1. 입력된 컨텐츠에서 http로 시작하는 글자 있는지 찾기
  const myurl = mydata.contents
    .split(' ')
    .filter((el) => el.includes('http'))[0]; // https://daum.net

  // 2. 만약 있다면, 찾은 주소로 axios.get 요청해서 html코드 받아오기 => 스크래핑
  const result = await axios.get(myurl);

  // 3. 스크래핑 결과에서 OG(오픈그래프) 코드 골라내서 변수에 저장하기
  const $ = cheerio.load(result.data);
  // attr 속성값을 가져옴
  // each(array, callback)
  $('meta').each((_, el) => {
    if ($(el).attr('property')) {
      const key = $(el).attr('property').split(':')[1];
      const value = $(el).attr('content');
      console.log(key, value);
    }
  });
}

const frontendData = {
  title: 'hello',
  contents:
    'https://www.naver.com'
};
createBoardAPI(frontendData);
profile
learn !

0개의 댓글