package main
import (
"context"
"io/ioutil"
"log"
"math"
"time"
"github.com/chromedp/cdproto/emulation"
"github.com/chromedp/cdproto/page"
"github.com/chromedp/chromedp"
)
func main() {
// 禁用chrome headless
opts := append(
chromedp.DefaultExecAllocatorOptions[:],
chromedp.NoDefaultBrowserCheck, //不检查默认浏览器
chromedp.Flag("headless", true),
chromedp.Flag("blink-settings", "imagesEnabled=true"), //开启图像界面,重点是开启这个
chromedp.Flag("ignore-certificate-errors", true), //忽略错误
chromedp.Flag("disable-web-security", true), //禁用网络安全标志
chromedp.Flag("disable-extensions", true), //开启插件支持
chromedp.Flag("disable-default-apps", true),
chromedp.NoFirstRun, //设置网站不是首次运行
chromedp.UserAgent("Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.164 Safari/537.36"), //设置UserAgent
)
allocCtx, cancel := chromedp.NewExecAllocator(context.Background(), opts...)
defer cancel()
// 创建上下文实例
ctx, cancel := chromedp.NewContext(
allocCtx,
chromedp.WithLogf(log.Printf),
)
defer cancel()
// 创建超时上下文
ctx, cancel = context.WithTimeout(ctx, 20*time.Second)
defer cancel()
// navigate to a page, wait for an element, click
// capture screenshot of an element
var buf []byte
// capture entire browser viewport, returning png with quality=90
if err := chromedp.Run(ctx, fullScreenshot(`https://weibo.com/nba`, 200, &buf)); err != nil {
log.Fatal(err)
}
if err := ioutil.WriteFile("./Screenshot.png", buf, 0644); err != nil {
log.Fatal(err)
}
log.Println("图片写入完成")
}
// fullScreenshot takes a screenshot of the entire browser viewport.
// Liberally copied from puppeteer's source.
// Note: this will override the viewport emulation settings.
func fullScreenshot(urlstr string, quality int64, res *[]byte) chromedp.Tasks {
//var htmlContent string
return chromedp.Tasks{
chromedp.Navigate(urlstr),
//chromedp.WaitVisible("style"),
chromedp.Sleep(10 * time.Second),
//chromedp.OuterHTML(`document.querySelector("body")`, &htmlContent, chromedp.ByJSPath),
chromedp.ActionFunc(func(ctx context.Context) error {
// get layout metrics
_, _, _, _, _, contentSize, err := page.GetLayoutMetrics().Do(ctx)
if err != nil {
return err
}
width, height := int64(math.Ceil(contentSize.Width)), int64(math.Ceil(contentSize.Height))
// force viewport emulation
err = emulation.SetDeviceMetricsOverride(width, height, 1, false).
WithScreenOrientation(&emulation.ScreenOrientation{
Type: emulation.OrientationTypePortraitPrimary,
Angle: 0,
}).
Do(ctx)
if err != nil {
return err
}
// capture screenshot
*res, err = page.CaptureScreenshot().
WithQuality(quality).
WithClip(&page.Viewport{
X: contentSize.X,
Y: contentSize.Y,
Width: contentSize.Width,
Height: contentSize.Height,
Scale: 1,
}).Do(ctx)
if err != nil {
return err
}
return nil
}),
}
}
go截图demo解决微博等无法截图问题
于 2021-11-12 00:11:34 首次发布