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

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

· 4년 전 · 1378

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

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

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

 

소스코드를 조금 수정하면 여러 많은 사이트들을 스크린샷 하여 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

댓글 작성

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

로그인하기

게시글 목록

번호 제목
1717265
1717252
1717247
1717243
1717237
1717225
1717214
1717208
1717203
1717189
1717183
1717177
1717172
1717163
1717162
1717156
1717154
1717153
1717141
1717140
1717138
1717113
1717111
1717105
1717099
1717085
1717076
1717072
1717065
1717062