编程笔记

lifelong learning & practice makes perfect

Go|chromedp全屏截图

1
2
3
4
5
6
7
8
9
10
11
12
13
func CaptureFullPage(urlstr string, quality int64) ([]byte, error) {
ctx, cancel := chromedp.NewContext(context.Background())
defer cancel()

var buf []byte
if err := chromedp.Run(ctx,
chromedp.Navigate(urlstr),
chromedp.FullScreenshot(&buf, quality), // 整页截图
); err != nil {
return nil, err
}
return buf, nil
}

默认的FullScreenshot截图,没有截全,只有部分(如A4打印后有3页,截图只有一页)

手动计算页面高度并截全页

控制设备模拟参数或定位截取区域,可通过 page.GetLayoutMetrics 获取页面内容宽高,再用 emulation.SetDeviceMetricsOverride 调整视窗,最后调用 page.CaptureScreenshot 并指定 clip 区域:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
import (
"context"
"math"
"os"
"github.com/chromedp/chromedp"
"github.com/chromedp/cdproto/emulation"
"github.com/chromedp/cdproto/page"
)

func CaptureFullPageManual(ctx context.Context, quality int64) ([]byte, error) {
// 获取页面布局尺寸
_, _, contentMetrics, _, _, _, err := page.GetLayoutMetrics().Do(ctx)
if err != nil {
return nil, err
}
width := int64(math.Ceil(contentMetrics.Width))
height := int64(math.Ceil(contentMetrics.Height))

// 强制设置设备视窗为内容大小
if err = emulation.SetDeviceMetricsOverride(width, height, 1, false).
WithScreenOrientation(&emulation.ScreenOrientation{
Type: emulation.OrientationTypePortraitPrimary,
Angle: 0,
}).Do(ctx); err != nil {
return nil, err
}

// 截全页
buf, err := page.CaptureScreenshot().
WithQuality(quality).
WithClip(&page.Viewport{
X: contentMetrics.X,
Y: contentMetrics.Y,
Width: contentMetrics.Width,
Height: contentMetrics.Height,
Scale: 1,
}).Do(ctx)
if err != nil {
return nil, err
}
return buf, nil
}

func main() {
ctx, cancel := chromedp.NewContext(context.Background())
defer cancel()

// 导航到目标页面
if err := chromedp.Run(ctx, chromedp.Navigate("https://example.com")); err != nil {
log.Fatal(err)
}

buf, err := CaptureFullPageManual(ctx, 90)
if err != nil {
log.Fatal(err)
}
if err := os.WriteFile("manual_full.png", buf, 0o644); err != nil {
log.Fatal(err)
}
}

参考

参考来源自 perplexity.ai:

欢迎关注我的其它发布渠道

Related Issues not found

Please contact @yiGmMk to initialize the comment