-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathscrapper_test.go
119 lines (93 loc) · 2.18 KB
/
scrapper_test.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
107
108
109
110
111
112
113
114
115
116
117
118
119
package scrapper
import (
"testing"
"fmt"
"strings"
)
func TestScrap(t *testing.T) {
hasKey := false
data := `
<body>
<div class="link">
<a href="www.google.com"> Test </a>
</div>
<div class="other_link">
<a href="www.facebook.com"> Test 2 </a>
</div>
</body>
`
scrapper := NewScrapper("", nil)
ret := scrapper.scrap(data, map[string]string{"test": "div.link a[href]"})
if len(ret) > 1 {
t.Errorf("The matched elements are more than 1 => %v", len(ret))
}
for k := range ret {
if k == "test" {
hasKey = true
break
}
}
if !hasKey {
t.Errorf("The key 'test' doesn't exists!")
}
first := ret["test"][0]
if len(first.Attr) > 1 {
t.Errorf("The data matched should have 1 attribute => %s", first.Attr)
}
for _, v := range first.Attr {
if v.Key == "href" {
if v.Val != "www.google.com" {
t.Errorf("href value of matched element should be www.google.com => %s", v.Val)
}
fmt.Printf("Link => %s\n", v.Val)
break
}
}
}
func TestDoScrapWithoutRouteSelector(t *testing.T) {
tags := map[string]string{
"googleImg": "div#lga img#hplogo[src]",
}
descriptor := NewDescriptor("", tags, nil)
scrapper := NewScrapper(
"http://www.google.com",
[]*ScrapDescriptor{
&descriptor,
})
ret := scrapper.DoScrap()
img := ret["googleImg@http://www.google.com"][0]
if img == nil {
t.Errorf("There was no img tag for Google")
}
for _, v := range img.Attr {
if v.Key == "src" {
if v.Val == "" {
t.Errorf("There is no src for image")
}
fmt.Printf("Google image Link => %s%s\n", scrapper.domain, v.Val)
break
}
}
}
func TestDoScrapWithRouteSelector(t *testing.T) {
tags := map[string]string{
"productTitle": "div.gb-list-cluster h3.gb-list-cluster-title",
}
descriptor := NewDescriptor("div.gb-category-submenu-title > a[href]", tags, nil)
scrapper := NewScrapper(
"http://www.garbarino.com",
[]*ScrapDescriptor{
&descriptor,
})
ret := scrapper.DoScrap()
if ret == nil {
t.Errorf("There was no result")
}
for key, title := range ret {
fmt.Printf("\n\nShowing key => %s\n", key)
for _, node := range title {
child := node.FirstChild
fmt.Println(strings.TrimSpace(child.Data))
}
}
}