Skip to content

Instantly share code, notes, and snippets.

@yehgdotnet
Created September 26, 2020 14:49
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save yehgdotnet/a0021a1da8f4b21441e46727283fc10a to your computer and use it in GitHub Desktop.
Save yehgdotnet/a0021a1da8f4b21441e46727283fc10a to your computer and use it in GitHub Desktop.
goscreenshot.go
//https://golangcode.com/headless-chrome-screenshot/
package main
import (
"context"
"io/ioutil"
"log"
"github.com/chromedp/cdproto/page"
"github.com/chromedp/chromedp"
)
func main() {
// Start Chrome
// Remove the 2nd param if you don't need debug information logged
ctx, cancel := chromedp.NewContext(context.Background(), chromedp.WithDebugf(log.Printf))
defer cancel()
url := "https://golangcode.com/"
filename := "golangcode.png"
// Run Tasks
// List of actions to run in sequence (which also fills our image buffer)
var imageBuf []byte
if err := chromedp.Run(ctx, ScreenshotTasks(url, &imageBuf)); err != nil {
log.Fatal(err)
}
// Write our image to file
if err := ioutil.WriteFile(filename, imageBuf, 0644); err != nil {
log.Fatal(err)
}
}
func ScreenshotTasks(url string, imageBuf *[]byte) chromedp.Tasks {
return chromedp.Tasks{
chromedp.Navigate(url),
chromedp.ActionFunc(func(ctx context.Context) (err error) {
*imageBuf, err = page.CaptureScreenshot().WithQuality(90).Do(ctx)
return err
}),
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment