如何将本地html加载到headless chrome



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

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

这可能吗?

是的。chromedp文档中有一个很好的例子https://github.com/chromedp/examples/blob/master/screenshot/main.go.唯一的区别在于;https://..."在urlstring中,您将使用";文件:///<absolute_path_to_your_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
}),
}
}

相关内容

  • 没有找到相关文章

最新更新