-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathparse_test.go
335 lines (308 loc) · 12.1 KB
/
parse_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
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
package pagser
import (
"fmt"
"net/http"
"strings"
"sync"
"testing"
"github.com/PuerkitoBio/goquery"
)
const rawParseHtml = `
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Pagser Example</title>
<meta name="keywords" content="golang,pagser,goquery,html,page,parser,colly">
</head>
<body>
<h1><u>Pagser</u> H1 Title</h1>
<div class="navlink">
<div class="container">
<ul class="clearfix">
<li id=""><a href="/">Index</a></li>
<li id="2"><a href="/list/web" title="web site">Web page</a></li>
<li id="3"><a href="/list/pc" title="pc page">Pc Page</a></li>
<li id="4"><a href="/list/mobile" title="mobile page">Mobile Page</a></li>
</ul>
</div>
</div>
<div class="words" show="true">A|B|C|D</div>
<div class="group" id="a">
<h2>Email</h2>
<ul>
<li class="item" id="1" name="email" value="pagser@foolin.github">pagser@foolin.github</li>
<li class="item" id="2" name="email" value="pagser@foolin.github">hello@pagser.foolin</li>
</ul>
</div>
<div class="group" id="b">
<h2>Bool</h2>
<ul>
<li class="item" id="3" name="bool" value="true">true</li>
<li class="item" id="4" name="bool" value="false">false</li>
</ul>
</div>
<div class="group" id="c">
<h2>Number</h2>
<ul>
<li class="item" id="5" name="number" value="12345">12345</li>
<li class="item" id="6" name="number" value="67890">67890</li>
</ul>
</div>
<div class="group" id="d">
<h2>Float</h2>
<ul>
<li class="item" id="7" name="float" value="123.45">123.45</li>
<li class="item" id="8" name="float" value="678.90">678.90</li>
</ul>
</div>
<div class="empty">
<span></span><span></span>
<div>
</body>
</html>
`
type ParseData struct {
Title string `pagser:"title"`
Keywords []string `pagser:"meta[name='keywords']->attrSplit(content)"`
H1 string `pagser:"h1"`
H1Text string `pagser:"h1->text()"`
H1TextEmpty string `pagser:"h1->textEmpty('')"`
TextEmptyNoData string `pagser:".empty->textEmpty('nodata')"`
H1Html string `pagser:"h1->html()"`
H1OutHtml string `pagser:"h1->outerHtml()"`
SameFuncValue string `pagser:"h1->SameFunc()"`
MyGlobalFuncValue string `pagser:"h1->MyGlobFunc()"`
MyStructFuncValue string `pagser:"h1->MyStructFunc()"`
FillFieldFuncValue string `pagser:"h1->FillFieldFunc()"`
FillFieldOtherValue string //Set value by FillFieldFunc()
NavList []struct {
ID int `pagser:"->attrEmpty(id, -1)"`
Link struct {
Name string `pagser:"->text()"`
Url string `pagser:"->attr(href)"`
AbsUrl string `pagser:"->absHref('https://thisvar.com')"`
} `pagser:"a"`
LinkHtml string `pagser:"a->html()"`
ParentFuncName string `pagser:"a->ParentFunc()"`
} `pagser:".navlink li"`
NavFirst struct {
ID int `pagser:"->attrEmpty(id, 0)"`
Name string `pagser:"a->text()"`
Url string `pagser:"a->attr(href)"`
} `pagser:".navlink li->first()"`
NavLast struct {
ID int `pagser:"->attrEmpty(id, 0)"`
Name string `pagser:"a->text()"`
Url string `pagser:"a->attr(href)"`
} `pagser:".navlink li->last()"`
SubStruct struct {
Label string `pagser:"label"`
Values []string `pagser:".item->eachAttr(value)"`
} `pagser:".group->eq(0)"`
SubPtrStruct *struct {
Label string `pagser:"label"`
Values []string `pagser:".item->eachAttr(value)"`
} `pagser:".group:last-child"`
NavFirstID int `pagser:".navlink li:first-child->attrEmpty(id, 0)"`
NavLastID uint `pagser:".navlink li:last-child->attr(id)"`
NavLastData string `pagser:".navlink li:last-child->attr(data, 'nodata')"`
NavFirstIDDefaultValue int `pagser:".navlink li:first-child->attrEmpty(id, -999)"`
NavTextList []string `pagser:".navlink li"`
NavEachText []string `pagser:".navlink li->eachText()"`
NavEachTextEmpty []string `pagser:".navlink li->eachTextEmpty('')"`
NavEachTextEmptyNoData []string `pagser:".empty span->eachTextEmpty('nodata')"`
NavEachAttrID []string `pagser:".navlink li->eachAttr(id)"`
NavEachAttrEmptyID []string `pagser:".navlink li->eachAttrEmpty(id, -1)"`
NavEachHtml []string `pagser:".navlink li->eachHtml()"`
NavEachOutHtml []string `pagser:".navlink li->eachOutHtml()"`
NavJoinString string `pagser:".navlink li->eachTextJoin(|)"`
NavEqText string `pagser:".navlink li->eqAndText(1)"`
NavEqAttr string `pagser:".navlink li->eqAndAttr(1, id)"`
NavEqHtml string `pagser:".navlink li->eqAndHtml(1)"`
NavEqOutHtml string `pagser:".navlink li->eqAndOutHtml(1)"`
NavSize int `pagser:".navlink li->size()"`
SubPageData *SubPageData `pagser:".navlink li:last-child"`
SubPageDataList []*SubPageData `pagser:".navlink li"`
WordsSplitArray []string `pagser:".words->textSplit(|)"`
WordsSplitArrayNoTrim []string `pagser:".words->textSplit('|', false)"`
WordsShow bool `pagser:".words->attrEmpty(show, false)"`
WordsConcatText string `pagser:".words->textConcat('this is words:', [, $value, ])"`
WordsConcatAttr string `pagser:".words->attrConcat(show, 'isShow = [', $value, ])"`
Email string `pagser:".item[name='email']->attr('value')"`
Emails []string `pagser:".item[name='email']->eachAttrEmpty(value, '')"`
CastBoolValue bool `pagser:".item[name='bool']->attrEmpty(value, false)"`
CastBoolNoExist bool `pagser:".item[name='bool']->attrEmpty(value2, false)"`
CastBoolArray []bool `pagser:".item[name='bool']->eachAttrEmpty(value, false)"`
CastIntValue int `pagser:".item[name='number']->attrEmpty(value, 0)"`
CastIntNoExist int `pagser:".item[name='number']->attrEmpty(value2, -1)"`
CastIntArray []int `pagser:".item[name='number']->eachAttrEmpty(value, 0)"`
CastInt32Value int32 `pagser:".item[name='number']->attrEmpty(value, 0)"`
CastInt32NoExist int32 `pagser:".item[name='number']->attrEmpty(value2, -1)"`
CastInt32Array []int32 `pagser:".item[name='number']->eachAttrEmpty(value, 0)"`
CastInt64Value int64 `pagser:".item[name='number']->attrEmpty(value, 0)"`
CastInt64NoExist int64 `pagser:".item[name='number']->attrEmpty(value2, -1)"`
CastInt64Array []int64 `pagser:".item[name='number']->eachAttrEmpty(value, 0)"`
CastFloat32Value float32 `pagser:".item[name='float']->attrEmpty(value, 0)"`
CastFloat32NoExist float32 `pagser:".item[name='float']->attrEmpty(value2, 0.0)"`
CastFloat32Array []float32 `pagser:".item[name='float']->eachAttrEmpty(value, 0)"`
CastFloat64Value float64 `pagser:".item[name='float']->attrEmpty(value, 0)"`
CastFloat64NoExist float64 `pagser:".item[name='float']->attrEmpty(value2, 0.0)"`
CastFloat64Array []float64 `pagser:".item[name='float']->eachAttrEmpty(value, 0)"`
NodeChild []struct {
Value string `pagser:"->text()"`
} `pagser:".group->child()"`
NodeChildSelector []struct {
Value string `pagser:"->text()"`
} `pagser:".group->child('h2')"`
NodeEqFirst struct {
Value string `pagser:"h2->text()"`
} `pagser:".group->eq(0)"`
NodeEqLast struct {
Value string `pagser:"h2->text()"`
} `pagser:".group->eq(-1)"`
NodeEqPrev []struct {
Value string `pagser:"->text()"`
} `pagser:".item:last-child->prev()"`
NodeEqPrevSelector struct {
Value string `pagser:"->text()"`
} `pagser:".item:last-child->prev('[id=\"1\"]')"`
NodeEqNext []struct {
Value string `pagser:"->text()"`
} `pagser:".item:first-child->next()"`
NodeEqNextSelector struct {
Value string `pagser:"->text()"`
} `pagser:".item:first-child->next('[id=\"2\"]')"`
NodeParent []struct {
Value string `pagser:"h2->text()"`
} `pagser:"h2:first-child->parent()"`
NodeParents []struct {
Value string `pagser:"h2->text()"`
} `pagser:"h2:first-child->parents()"`
NodeParentsSelector []struct {
Value string `pagser:"h2->text()"`
} `pagser:"h2:first-child->parents('[id=\"b\"]')"`
NodeParentsUntil []struct {
Value string `pagser:"h2->text()"`
} `pagser:"h2:first-child->parentsUntil('[id=\"b\"]')"`
NodeParentSelector []struct {
Value string `pagser:"h2->text()"`
} `pagser:"h2:first-child->parent('[id=\"a\"]')"`
NodeEqSiblings []struct {
Value string `pagser:"->text()"`
} `pagser:".item:first-child->siblings()"`
NodeEqSiblingsSelector []struct {
Value string `pagser:"->text()"`
} `pagser:".item:first-child->siblings('[id=\"2\"]')"`
}
// this method will auto call, not need register.
func MyGlobalFunc(selection *goquery.Selection, args ...string) (out interface{}, err error) {
return "Global-" + selection.Text(), nil
}
// this method will auto call, not need register.
func SameFunc(selection *goquery.Selection, args ...string) (out interface{}, err error) {
return "Global-Same-Func-" + selection.Text(), nil
}
// this method will auto call, not need register.
func (pd ParseData) MyStructFunc(selection *goquery.Selection, args ...string) (out interface{}, err error) {
return "Struct-" + selection.Text(), nil
}
func (pd ParseData) ParentFunc(selection *goquery.Selection, args ...string) (out interface{}, err error) {
return "ParentFunc-" + selection.Text(), nil
}
// this method will auto call, not need register.
func (pd *ParseData) FillFieldFunc(selection *goquery.Selection, args ...string) (out interface{}, err error) {
text := selection.Text()
pd.FillFieldOtherValue = "This value is set by the FillFieldFunc() function -" + text
return "FillFieldFunc-" + text, nil
}
func (pd *ParseData) SameFunc(selection *goquery.Selection, args ...string) (out interface{}, err error) {
return "Struct-Same-Func-" + selection.Text(), nil
}
type SubPageData struct {
Text string `pagser:"->text()"`
SubFuncValue string `pagser:"->SubFunc()"`
ParentFuncValue string `pagser:"->ParentFunc()"`
SameFuncValue string `pagser:"->SameFunc()"`
}
func (spd SubPageData) SubFunc(selection *goquery.Selection, args ...string) (out interface{}, err error) {
return "SubFunc-" + selection.Text(), nil
}
func (spd SubPageData) SameFunc(selection *goquery.Selection, args ...string) (out interface{}, err error) {
return "Sub-Struct-Same-Func-" + selection.Text(), nil
}
// Page parse from https://httpbin.org
type HttpBinData struct {
Title string `pagser:"title"`
Version string `pagser:".version->text()"`
Description string `pagser:".description->text()"`
}
func TestParse(t *testing.T) {
p := New()
//register global function
p.RegisterFunc("MyGlobFunc", MyGlobalFunc)
p.RegisterFunc("SameFunc", SameFunc)
var data ParseData
err := p.Parse(&data, rawParseHtml)
if err != nil {
t.Fatal(err)
}
fmt.Printf("json: %v\n", prettyJson(data))
}
func TestPagser_ParseDocument(t *testing.T) {
cfg := Config{
TagName: "pagser",
FuncSymbol: "->",
CastError: true,
Debug: true,
}
p, err := NewWithConfig(cfg)
if err != nil {
t.Fatal(err)
}
//register global function
p.RegisterFunc("MyGlobFunc", MyGlobalFunc)
p.RegisterFunc("SameFunc", SameFunc)
var data ParseData
doc, err := goquery.NewDocumentFromReader(strings.NewReader(rawParseHtml))
if err != nil {
t.Fatal(err)
}
err = p.ParseDocument(&data, doc)
//err = p.ParseSelection(&data, doc.Selection)
if err != nil {
t.Fatal(err)
}
fmt.Printf("json: %v\n", prettyJson(data))
}
func TestPagser_ParseReader(t *testing.T) {
res, err := http.Get("https://httpbin.org")
if err != nil {
t.Fatal(err)
}
defer res.Body.Close()
p := New()
var data HttpBinData
err = p.ParseReader(&data, res.Body)
if err != nil {
t.Fatal(err)
}
fmt.Printf("json: %v\n", prettyJson(data))
}
func TestPagser_RegisterFunc(t *testing.T) {
threads := 1000
p := New()
var wg sync.WaitGroup
for i := 0; i < threads; i++ {
wg.Add(1)
go func() {
for j := 0; j < 10; j++ {
for k, v := range builtinFuncs {
p.RegisterFunc(k, v)
}
}
wg.Done()
}()
}
wg.Wait()
}