【備忘録】GoからHeadless Chromeを動かしてスクリーンショットを撮る

TL;DR

package main

import (
    "path/filepath"

    "github.com/go-rod/rod"
    "github.com/go-rod/rod/lib/proto"
    "github.com/go-rod/rod/lib/utils"
)

func main() {
    browser := rod.New().MustConnect()

    page := browser.MustPage(TARGET_SITE_URL).MustSetViewport(1920, 1080, 0, false).MustWaitLoad()

    img, err := page.Screenshot(true, &proto.PageCaptureScreenshot{
        Format: proto.PageCaptureScreenshotFormatPng,
        Clip: &proto.PageViewport{
            X:      0,
            Y:      0,
            Width:  1920,
            Height: 1080,
            Scale: 2,
        },
        CaptureBeyondViewport: true,
        OptimizeForSpeed:      true,
        FromSurface:           true,
    })
    if err != nil {
        panic(err)
    }

    err = utils.OutputFile(filepath.Join(SAVE_DIR, "my.png"), img)
    if err != nil {
        panic(err)
    }
}

パフォーマンス

go-headlesschrome-example/screenshots.go at main · cateiru/go-headlesschrome-example · GitHubを使用して測定。

最低、1秒ほどかかるっぽい。