没啥水准,以前用过拿来记录一下。
简介
支持Chrome DevTools Protocol 的一个驱动浏览器的库。并且它不需要依赖其他的外界服务,是用golang写的,chromedp + chrome放在一起用。功能类似之前用过的selenium。
实战 - 截屏
package main
import (
"context"
"crypto/md5"
"encoding/base64"
"encoding/hex"
"github.com/chromedp/chromedp"
"io/ioutil"
"log"
"strings"
"time"
)
func main() {
options := []chromedp.ExecAllocatorOption{
chromedp.Flag("headless", true),
chromedp.UserAgent(`Mozilla/5.0 (Windows NT 6.3; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/73.0.3683.103 Safari/537.36`),
}
options = append(chromedp.DefaultExecAllocatorOptions[:], options...)
allocCtx, cancel := chromedp.NewExecAllocator(context.Background(), options...)
defer cancel()
// 创建chrome示例
ctx, cancel := chromedp.NewContext(allocCtx)
defer cancel()
ctx, cancel = context.WithTimeout(ctx, 5*time.Second)
defer cancel()
screenshot(ctx,"https://www.baidu.com","baidu")
}
func screenshot(ctx context.Context, url, name string) []byte{
// capture screenshot of an element
var buf []byte
// capture entire browser viewport, returning png with quality=90
if err := chromedp.Run(ctx, fullScreenshotHandle(url, 90, &buf)); err != nil {
log.Fatal(err)
}
if err := ioutil.WriteFile(name+"_fullScreenshot.png", buf, 0o644); err != nil {
log.Fatal(err)
}
log.Printf("wrote fullScreenshot.png")
return buf
}
// fullScreenshotHandle takes a screenshot of the entire browser viewport.
func fullScreenshotHandle(urlstr string, quality int, res *[]byte) chromedp.Tasks {
return chromedp.Tasks{
chromedp.Navigate(urlstr),
chromedp.FullScreenshot(res, quality),
}
}
//byte2base64 把图片转为 base64 格式并输出对应的 md5 校验码
func byte2base64(ctx context.Context, pngByte []byte) (base64Str, md5Str string) {
base64Str = base64.StdEncoding.EncodeToString(pngByte)
h := md5.New()
h.Write(pngByte)
md5Str = strings.ToUpper(hex.EncodeToString(h.Sum(nil)))
return
}
官方GitHub地址
https://github.com/chromedp/chromedp
文章评论