Backend 백엔드

[ 32 ] 오픈그래프 스크랩핑

박민우_ 2024. 8. 21. 23:34

오픈그래프 이해

디스코드나 카카오톡 등에서 URL 을 입력하면 아래와 같이 웹사이트의 이미지와 설명이 예쁘게 같이 출력된다. 

원리

사이트가 URL 을 인식하고, 그 URL에 get 요청을 통해서 HTML 파일을 받아 온다.

이 HTML 파일에서 이미지와 설명을 스크랩 해서 위의 이미지와 같이 이쁘게 출력을 한다.

 

오픈그래프 실습하기 

라이브러리 설치 

yarn add axios
yarn add cheerio

 

스크랩핑 함수 

실제 네이버 사이트의 HTML

 // 1. 입력된 메시지에서 http로 시작하는 문장이 있는지 먼저 찾기! ( find() 등의 알고리즘 사용하기 )

function findHttpMessage(input) {
    // input 문자열을 줄 단위로 나누기
    const lines = input.split('\n');
    
    // 각 줄을 검사하여 http로 시작하는지 확인
    for (let i = 0; i < lines.length; i++) {
        if (lines[i].trim().startsWith('http')) {
            return lines[i].trim(); // http로 시작하는 줄을 반환
        }
    }
    
    // http로 시작하는 문장이 없으면 null 반환
    return null;
}

// 예시
const input = `안녕하세요
여기 링크가 있어요 http://example.com
이건 그냥 텍스트입니다`;

console.log(findHttpMessage(input));  // "http://example.com" 반환
import axios from 'axios'
import cheerio from 'cheerio'

const createMessage = async()=>{
	
    
    const url = 'https://www.naver.com'
    
    // 2. axios.get으로 요청해서 html코드 받아오기 => 스크래핑
    const result = await axios.get(url)
    
    // 3. 스크래핑 결과에서 OG ( 오픈그래프 ) 코드를 골라내서 변수에 담기 => cheerio 도움 받기 
    
    const $ = cheerio.load(result.data)
    $("meta").each((index,el)=>{
    
    	if($(el).attr("property") && $(el).attr('property').includes("og:")){
        	const key = $(el).attr('property')
            const value = $(el).attr('content')
            console.log(key,value)
        }
    })
    
    
}

결과 

 

728x90