-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathget.go
106 lines (88 loc) · 1.82 KB
/
get.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
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
package gohtml
import (
"golang.org/x/net/html"
"strings"
)
func matchSelector(n *html.Node, selector string) bool {
var t int
var val string
switch selector[0] {
case '.':
t = 1
val = selector[1:]
case '#':
t = 2
val = selector[1:]
default:
t = 0
}
if n.Type != html.ElementNode {
return false
}
if t == 0 {
if n.Data == selector {
return true
}
} else {
for _, a := range n.Attr {
switch t {
case 1:
if a.Key == "class" && strings.Index(a.Val, val) >= 0 {
return true
}
case 2:
if a.Key == "id" && a.Val == val {
return true
}
}
}
}
return false
}
func GetNodeBySelector(n *html.Node, selector string) *html.Node {
if matchSelector(n, selector) {
return n
}
for c := n.FirstChild; c != nil; c = c.NextSibling {
if nn := GetNodeBySelector(c, selector); nn != nil {
return nn
}
}
return nil
}
func GetNodesBySelector(n *html.Node, selector string) (nodes []*html.Node) {
if matchSelector(n, selector) {
nodes = append(nodes, n)
}
for c := n.FirstChild; c != nil; c = c.NextSibling {
nodes = append(nodes, GetNodesBySelector(c, selector)...)
}
return
}
func GetNodeByTag(n *html.Node, tag string) *html.Node {
if n.Type == html.ElementNode && n.Data == tag {
return n
}
for c := n.FirstChild; c != nil; c = c.NextSibling {
if nod := GetNodeByTag(c, tag); nod != nil {
return nod
}
}
return nil
}
func GetNodesByTag(n *html.Node, tag string) (nodes []*html.Node) {
if n.Type == html.ElementNode && n.Data == tag {
nodes = append(nodes, n)
}
for c := n.FirstChild; c != nil; c = c.NextSibling {
nodes = append(nodes, GetNodesByTag(c, tag)...)
}
return
}
func GetChildNodes(n *html.Node) []*html.Node {
var nodes []*html.Node
for c := n.FirstChild; c != nil; c = c.NextSibling {
nodes = append(nodes, c)
}
return nodes
}