20220121 TIL (스크래핑&크롤링)

한결·2022년 1월 22일
0

TIL(Today I Learned)

목록 보기
10/14

스크래핑

스크래핑은 스크랩 하는 것이다.
특정 웹사이트에서 html을 가져온다.


유저가 보낸 정보에서 http가 포함된 url에서의 open graph 내용을 긁어오는 것이다.

yarn add cheerio명령어로 cheerio를 설치하고 import해온다

import cheerio from 'cheerio'

const mydata = {
    title:"안녕하세요~~~",
    contents: "여기 정말 좋아요 ~~~ 꼭 한번 놀러오세요 https://naver.com"
}

가 있을때 ,
이 url에서 스크래핑 하는 함수를 만들어 본다.

async function getOpenGraph(){
    const myaddress = mydata.contents.split("").filter((el)=>el.includes("http"))
    const html = await axios.get(myaddress[0])
    const $ = cheerio.load(html.data)
    $('meta').each((_, el)=>{
        if($(el).attr('property)){
            const key=$(el).attr('property).split(":")[1]
        }
  })
     console.log(html)
}

const myaddress = mydata.contents.split("").filter((el)=>el.includes("http"))

문자열을 ""로 쪼개고, http가 들어있는 인자를 찾는다.

  • 일단 url로 이동해서 html을 가져와야 한다.

    import axios from 'axios'

을 사용해준다.

const $ = cheerio.load(html.data)

html 데이터를 cheerio에 넘겨준다

$('meta').each((_, el)=>{
       if($(el).attr('property)){
            const key=$(el).attr('property).split(":")[1]
        }

meta태그들만 찾아서 가져오고, 각 마다 돌면서 콜백함수 실행. property가 없으면 종료
og:title을 :로 분리하면 1번째가 title

크롤링

스크래핑을 정기적 주기적으로 여러번 하는 것.

yarn add puppeteer명령어로 puppeteer를 설치하고 import한다

import puppeteer from 'puppeteer'

async function startCrawling(){
    const browser = await puppeteer.launch({ headless : false })
    const page = await browser.newPage()
    await page.setViewport({ width:1280, height:720 })
    await page.goto("https://www.goodchoice.kr/product/search/2")
    await page.waitForTimeout(1000)
    }

크로미엄이란 브라우저를 나타나게 한다

실습

iframe태그 안에 있는 html 가져오기

async function startCrawling(){
    const browser = await puppeteer.launch({ headless : false })
    const page = await browser.newPage()
    await page.setViewport({ width:1280, height:720 })
    await page.goto("https://finance.naver.com/item/sise.naver?code=005930")   
    const myIframePage = await page.frames().find(iframe => iframe.url().includes("/item/sise_day.naver?code=005930"))


    for(let i =3 ; i<=7; i++){
        await page.waitForTimeout(2000)
       
        
        const mydate = await myIframePage.$eval(`body > table.type2 > tbody > tr:nth-child(${i}) > td:nth-child(1) > span`,el => el.textContent)
        const myprice = await myIframePage.$eval(`body > table.type2 > tbody > tr:nth-child(${i}) > td:nth-child(2) > span`,el => el.textContent)
        const stock = new Stock({
                    name: "삼성전자",
                    date: mydate,
                    price: Number(myprice.replace(",",""))
        })
     
        await stock.save()
        console.log(`날짜:${mydate},가격: ${myprice}`)
    }
    
  
    await browser.close()
}

를 한다면 같은 결과가 나오는걸 볼 수 있다.

0개의 댓글