Go 如何将本地html加载到headless chrome

Go 如何将本地html加载到headless chrome,go,google-chrome-headless,chromedp,Go,Google Chrome Headless,Chromedp,我有本地html文件,我需要渲染它们并获取它们的屏幕截图 我找不到在chromedp中加载html代码的任何解决方案 有可能吗?是的,有可能。 在文档中有一个很好的例子。唯一的区别是,不使用“https://...在urlstring中,您将使用“file://” 代码示例,我主要从示例链接中获取,用于制作存储在本地系统上的html屏幕截图: package main import ( "context" "io/ioutil"

我有本地html文件,我需要渲染它们并获取它们的屏幕截图

我找不到在chromedp中加载html代码的任何解决方案

有可能吗?

是的,有可能。 在文档中有一个很好的例子。唯一的区别是,不使用“https://...在urlstring中,您将使用“file://”

代码示例,我主要从示例链接中获取,用于制作存储在本地系统上的html屏幕截图:

package main

import (
    "context"
    "io/ioutil"
    "log"
    "math"

    "github.com/chromedp/cdproto/emulation"
    "github.com/chromedp/cdproto/page"
    "github.com/chromedp/chromedp"
)

func main() {
    // create context
    ctx, cancel := chromedp.NewContext(context.Background())
    defer cancel()
    //if you want to use html from your local filesystem use file:/// + absolute path to your html file
    url :=  "file:///home/oktogen/Documents/Notebooks/2020/May/AnalysisJobs/FlaskApp/templates/index.html"
    // capture screenshot of an element
    var buf []byte
    // capture entire browser viewport, returning png with quality=90
    if err := chromedp.Run(ctx, fullScreenshot(url, 90, &buf)); err != nil {
        log.Fatal(err)
    }
    if err := ioutil.WriteFile("fullScreenshot.png", buf, 0644); err != nil {
        log.Fatal(err)
    }
}

// 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 {
    return chromedp.Tasks{
        chromedp.Navigate(urlstr),
        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
        }),
    }
}