테스트 사이트 - 개발 중인 베타 버전입니다

golang 자동화 사이트 스크린샷 찍기

· 4년 전 · 1380

휴가 나와서 집에 있는 동안은 게임이 질려서

할 게 없으니 생각난 소모임.

고로 자동으로 사이트 스크린샷하기.

 

소스코드를 조금 수정하면 여러 많은 사이트들을 스크린샷 하여 DB에 올릴 수도 있고...

더 수정하면 여러 페이지를 스크린샷하여 과거 데이터와 비교할 수도 있고....

 

chromedb 라이브러리를 이용하면 이미지 다운로드, 업로드... PDF 따기...

등등 진짜 웹에서 가능한 모든 일을 할 수 있을 정도로 무궁무진..

 

 

package main

import (
   "context"
   "github.com/chromedp/cdproto/emulation"
   "github.com/chromedp/cdproto/page"
   "github.com/chromedp/chromedp"
   "io/ioutil"
   "log"
   "math"
)

func main() {
   context, cancel := chromedp.NewContext(
      context.Background(),
   )
   defer cancel()

   // 스크린샷을 담기 위한 함수
   var buf []byte

   if err := chromedp.Run(context, fullScreenShot(`https://sir.kr/`, 100, &buf)); err != nil {
      log.Fatalln(err)
   }

   if err := ioutil.WriteFile("fullScreenshot.png", buf, 0664); err != nil {
      log.Fatalln(err)
   }
}

// 화면 전체를 스크린 샷 찍기.
// 출처 - https://github.com/chromedp/examples/blob/master/screenshot/main.go
func fullScreenShot(url string, quality int64, res *[]byte) chromedp.Tasks {
   return chromedp.Tasks{
      chromedp.Navigate(url),
      chromedp.ActionFunc(func(ctx context.Context) error {
         // get layout metrics
         _, _, cssContentSize, err := page.GetLayoutMetrics().Do(ctx)
         if err != nil {
            return err
         }

         width, height := int64(math.Ceil(cssContentSize.Width)), int64(math.Ceil(cssContentSize.Height))

         // force viewport emulation
         err = emulation.SetDeviceMetricsOverride(width, height, 1, false).
            WithScreenOrientation(&emulation.ScreenOrientation{
               Type:  emulation.OrientationTypePortraitPrimary,
               Angle: 0,
            }).
            Do(ctx)
         if err != nil {
            return err
         }

         // capture screenshot
         *res, err = page.CaptureScreenshot().
            WithQuality(quality).
            WithClip(&page.Viewport{
               X:      cssContentSize.X,
               Y:      cssContentSize.Y,
               Width:  cssContentSize.Width,
               Height: cssContentSize.Height,
               Scale:  1,
            }).Do(ctx)
         if err != nil {
            return err
         }

         return nil
      }),
   }
}

 

 

31596994_1619021226.8658.png

 

 

 

 
 

 

31596994_1619021222.619.png

댓글 작성

댓글을 작성하시려면 로그인이 필요합니다.

로그인하기

게시글 목록

번호 제목
1717479
1717473
1717470
1717463
1717452
1717438
1717431
1717422
1717414
1717412
1717407
1717401
1717393
1717386
1717379
1717378
1717365
1717364
1717360
1717359
1717346
1717344
1717333
1717327
1717313
1717312
1717310
1717307
1717306
1717304