-
Notifications
You must be signed in to change notification settings - Fork 1
/
filters.go
93 lines (82 loc) · 2.38 KB
/
filters.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
package scrappy
import (
"golang.org/x/net/html"
"strings"
)
// FilterFunc is the general definition of a node filter
type FilterFunc func(node *html.Node) bool
// Tag s a filter func that return a node that matches with a given string
func Tag(val string) FilterFunc {
return func(node *html.Node) bool { return node.Type == html.ElementNode && node.Data == val }
}
// Text is a filter func that return a node that matches with a given string
func Text(val string) FilterFunc {
return func(node *html.Node) bool {
return node.Type == html.TextNode && node.Data == val
}
}
// Attr is a filter func that return a node that matches with a given string
func Attr(val string) FilterFunc {
return func(node *html.Node) bool {
for _, a := range node.Attr {
if a.Key == val {
return true
}
}
return false
}
}
// Values is a filter func that return a node that matches with a given string
func Value(val string) FilterFunc {
return func(node *html.Node) bool {
for _, a := range node.Attr {
if a.Val == val {
return true
}
}
return false
}
}
// AttrVal is a filter func that return a node that matches with a pair attr/value
func AttrVal(attr string, val string) FilterFunc {
return func(node *html.Node) bool {
for _, a := range node.Attr {
if a.Key == attr && a.Val == val {
return true
}
}
return false
}
}
// ContainTag is a filter func that return a node with a tag that contain a given string
func ContainsTag(val string) FilterFunc {
return func(node *html.Node) bool { return node.Type == html.ElementNode && strings.Contains(node.Data, val) }
}
// ContainText is a filter func that return a node that contain a given string
func ContainsText(val string) FilterFunc {
return func(node *html.Node) bool {
return node.Type == html.TextNode && strings.Contains(node.Data, val)
}
}
// ContainAttr is a filter func that return a node with an attr that contain a given string
func ContainsAttr(val string) FilterFunc {
return func(node *html.Node) bool {
for _, a := range node.Attr {
if strings.Contains(a.Key, val) {
return true
}
}
return false
}
}
// AttrValues is a filter func that return a node with an attr value that contain a given string
func ContainsValue(val string) FilterFunc {
return func(node *html.Node) bool {
for _, a := range node.Attr {
if strings.Contains(a.Val, val) {
return true
}
}
return false
}
}