Created
December 7, 2022 11:28
-
-
Save olliephillips/5a394dfd9a5dc3266279f48a8d68a2ea to your computer and use it in GitHub Desktop.
Screenshot in Go with Chrome Headless
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"context" | |
"log" | |
"time" | |
"github.com/chromedp/chromedp" | |
) | |
func main() { | |
// create context | |
ctx, cancel := chromedp.NewContext(context.Background()) | |
defer cancel() | |
// capture screenshot of a specific element | |
var buf []byte | |
if err := chromedp.Run(ctx, fullScreenshot(`https://google.com`, &buf)); err != nil { | |
log.Fatal(err) | |
} | |
// save the screenshot to disk | |
if err := ioutil.WriteFile("screenshot.png", buf, 0644); err != nil { | |
log.Fatal(err) | |
} | |
} | |
// fullScreenshot takes a screenshot of the entire browser viewport. | |
// | |
// Note: this will require a larger memory allocation than taking a screenshot | |
// of a specific element. | |
func fullScreenshot(urlstr string, res *[]byte) chromedp.Tasks { | |
return chromedp.Tasks{ | |
chromedp.Navigate(urlstr), | |
chromedp.WaitVisible(`body`, chromedp.ByQuery), | |
chromedp.Screenshot(`body`, res, chromedp.NodeVisible, chromedp.ByQuery), | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment