Created
January 24, 2017 15:54
-
-
Save peterhellberg/f21469d555d3ff4dfc2846c426eea987 to your computer and use it in GitHub Desktop.
Using chromedp to take screenshots
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" | |
"io/ioutil" | |
"log" | |
"time" | |
cdp "github.com/knq/chromedp" | |
) | |
func main() { | |
var err error | |
// create context | |
ctxt, cancel := context.WithCancel(context.Background()) | |
defer cancel() | |
// create chrome instance | |
c, err := cdp.New(ctxt) | |
if err != nil { | |
log.Fatal(err) | |
} | |
// run task list | |
var buf []byte | |
err = c.Run(ctxt, screenshot(`http://www.cmore.se/film/3643033-deadpool`, `#main-wrapper`, &buf)) | |
if err != nil { | |
log.Fatal(err) | |
} | |
// shutdown chrome | |
err = c.Shutdown(ctxt) | |
if err != nil { | |
log.Fatal(err) | |
} | |
// wait for chrome to finish | |
err = c.Wait() | |
if err != nil { | |
log.Fatal(err) | |
} | |
err = ioutil.WriteFile("deadpool.png", buf, 0644) | |
if err != nil { | |
log.Fatal(err) | |
} | |
} | |
func screenshot(urlstr, sel string, res *[]byte) cdp.Tasks { | |
return cdp.Tasks{ | |
cdp.Navigate(urlstr), | |
cdp.Sleep(2 * time.Second), | |
cdp.WaitVisible(sel, cdp.ByID), | |
cdp.Screenshot(sel, res, cdp.ElementVisible, cdp.ByID), | |
} | |
} |
Author
peterhellberg
commented
Jan 24, 2017
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment