Go语言实现谷歌浏览器截屏效果:突破传统截屏技术的创新

admin2023-10-30电脑应用浏览:133

在这篇文章中,我们将研究如何利用Chrome的调试协议来加载网页并截图。通过一个名为的程序包chromedp,一切都可以实现,该程序包使我们可以通过Go代码控制Chrome实例。您还需要安装Chrome或使用类似于chrome/headless-shellDocker映像的工具。

我们将代码中的过程分为:

转自go语言中文文档:www.topgoer.com

  • 启动Chrome
  • 运行任务:例如加载网页并截图
  • 将屏幕截图保存到文件
package mainimport (    "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://www.topgoer.com/"    filename := "topgoer.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        }),    }}

另外,如果您想将页面另存为pdf而不是图像,则可以将CaptureScreenshot行替换为以下内容:

    *imageBuf, _, err = page.PrintToPDF().WithPrintBackground(false).Do(ctx)

热门文章