-
-
Notifications
You must be signed in to change notification settings - Fork 17
/
rendering.go
90 lines (72 loc) · 2.17 KB
/
rendering.go
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
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
// Package rendering provides a function to render HTML to images or HTML after JS execution.
// It uses the Chrome Debug Protocol through the rod package. It will download a headless
// Chrome version if needed that matches the current platform.
//
// If the environment variable SND_DEBUG=1 it will start the chrome instances
// in non-headless mode.
package rendering
import (
"bytes"
"errors"
"image"
_ "image/png"
"net/url"
"os"
"time"
"github.com/go-rod/rod/lib/launcher"
"github.com/go-rod/rod"
"github.com/go-rod/rod/lib/proto"
)
var browser *rod.Browser
func init() {
if os.Getenv("SND_DEBUG") == "1" {
l := launcher.New().
Headless(false).
Devtools(true)
browser = rod.New().ControlURL(l.MustLaunch()).MustConnect()
} else {
browser = rod.New().MustConnect()
}
}
func screenshotPage(page *rod.Page, width int) (image.Image, error) {
imageData, err := page.MustSetViewport(width, 10000, 1.0, false).MustElement("body").Screenshot(proto.PageCaptureScreenshotFormatPng, 100)
if err != nil {
return nil, err
}
img, _, err := image.Decode(bytes.NewBuffer(imageData))
if err != nil {
return nil, err
}
if img.Bounds().Max.Y >= 9500 {
return nil, errors.New("too large")
}
return img, nil
}
// RenderHTML renders the element #content into an image.
func RenderHTML(html string, width int) (image.Image, error) {
page := browser.MustPage("data:text/html," + url.PathEscape(html))
page.MustWaitLoad().MustWaitIdle()
defer page.Close()
return screenshotPage(page, width)
}
// RenderURL opens the URL and renders the element #content into an image.
func RenderURL(url string, width int) (image.Image, error) {
page := browser.MustPage(url)
page.MustWaitLoad().MustWaitIdle()
defer page.Close()
return screenshotPage(page, width)
}
// ExtractHTML opens the URL, lets the page executes and returns the HTML.
func ExtractHTML(url string, selector string) (string, error) {
page := browser.MustPage(url)
page.MustWaitLoad().MustWaitIdle()
defer page.Close()
if err := page.Timeout(time.Second*5).WaitElementsMoreThan(selector, 0); err != nil {
return "", err
}
sel, err := page.Element(selector)
if err != nil {
return "", err
}
return sel.HTML()
}