/
image.go
64 lines (58 loc) · 1.25 KB
/
image.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
package goscrapper
import (
"github.com/PuerkitoBio/goquery"
)
// get slice of all images on the page with absolute URLs
//
// Example:
//
// html: <img src="https://test-pages.de/assets/cat.jpg" alt="absolute path">
//
// Result: ['https://test-pages.de/assets/cat.jpg']
func (w *Web) Images() []string {
var images []string
w.Doc.Find("img").Each(func(i int, img *goquery.Selection) {
url, ok := img.Attr("src")
if ok {
images = append(images, url)
}
})
return images
}
// get all images on the page with commonly interesting details
//
// Example:
//
// html: <img src="https://test-pages.de/assets/cat.jpg" alt="absolute path">
//
// Result: [
// 'url' => 'https://test-pages.de/assets/cat.jpg',
// 'alt' => 'absolute path',
// 'width' => null,
// 'height' => null,
// ]
func (w *Web) ImagesWithDetails() []map[string]interface{} {
var images []map[string]interface{}
nodes := w.Doc.Find("img").Nodes
for _, node := range nodes {
details := make(map[string]interface{})
for _, n := range node.Attr {
if allowed(n.Key) {
details[n.Key] = n.Val
}
}
images = append(images, details)
}
return images
}
func allowed(attr string) bool {
switch attr {
case
"alt",
"src",
"width",
"height":
return true
}
return false
}