-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbrowser_extractor.go
349 lines (319 loc) · 9.08 KB
/
browser_extractor.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
336
337
338
339
340
341
342
343
344
345
346
347
348
349
package extractor
import (
"fmt"
"regexp"
"sort"
"strings"
"time"
"github.com/go-rod/rod"
"github.com/go-rod/rod/lib/launcher"
)
type BrowserExtractor struct {
Config ExtractorConfig
Browser *rod.Browser
}
func NewBrowserExtractor(config ExtractorConfig) *BrowserExtractor {
launcher := rod.New().ControlURL(launcher.New().Set("--no-sandbox").MustLaunch())
browser := launcher.MustConnect()
return &BrowserExtractor{Config: config, Browser: browser}
}
func (e *BrowserExtractor) Extract(url string) (*ExtractionResult, error) {
result := &ExtractionResult{
SchemaResults: make(map[string]SchemaResult),
Errors: make([]ExtractionError, 0),
}
page := e.Browser.MustPage(url)
defer page.Close()
page.MustWaitStable()
result.FinalURL = page.MustInfo().URL
// Extract items for each schema
for _, schema := range e.Config.Schemas {
schemaResult := SchemaResult{
Schema: SchemaInfo{
Name: schema.Name,
EntityType: schema.EntityType,
},
Items: make([]ExtractedItem, 0),
}
elements, err := page.ElementsX(schema.Selector)
if err != nil {
result.Errors = append(result.Errors, ExtractionError{
Field: schema.Name,
Message: fmt.Sprintf("failed to find elements with selector: %s", schema.Selector),
URL: url,
})
continue
}
for _, element := range elements {
item, errs := e.extractItemWithSchema(element, url, schema)
if len(errs) > 0 {
result.Errors = append(result.Errors, errs...)
}
if item != nil {
// extract external_id
if externalID, ok := extractExternalID(item); ok {
item["external_id"] = strings.ToUpper(externalID)
delete(item, "_id")
}
// extract external_time
if externalTime, ok := extractExternalTime(item); ok {
item["external_time"] = externalTime
delete(item, "_time")
} else {
item["external_time"] = time.Now()
}
schemaResult.Items = append(schemaResult.Items, item)
}
}
result.SchemaResults[schema.Name] = schemaResult
}
return result, nil
}
func (e *BrowserExtractor) extractItemWithSchema(element *rod.Element, url string, schema Schema) (ExtractedItem, []ExtractionError) {
item := make(ExtractedItem)
var errors []ExtractionError
for _, field := range schema.Fields {
value, err := e.extractField(element, field)
if err != nil {
errors = append(errors, ExtractionError{
Field: field.Name,
Message: err.Error(),
URL: url,
})
continue
}
item[field.Name] = value
}
return item, errors
}
func (e *BrowserExtractor) extractField(element *rod.Element, field Field) (interface{}, error) {
if strings.HasPrefix(field.Name, "_id") {
// extract nested id
if field.Type == "nested" {
nestedElement, err := element.ElementX(".")
if err != nil {
return nil, fmt.Errorf("nested element not found for selector: %s", field.Selector)
}
nestedItem := make(ExtractedItem)
for _, nestedField := range field.Fields {
nestedValue, err := e.extractField(nestedElement, nestedField)
if err != nil {
continue
}
nestedItem[nestedField.Name] = nestedValue
}
if len(nestedItem) > 0 {
return nestedItem, nil
}
}
// if nested id not found, extract id from url or element
var id string
switch field.From {
case FromURL:
url := element.Page().MustInfo().URL
matches := regexp.MustCompile(field.Pattern).FindStringSubmatch(url)
if len(matches) > 1 {
id = strings.Join(matches[1:], "/")
} else {
return nil, fmt.Errorf("failed to extract id from URL using pattern: %s", field.Pattern)
}
case FromElement:
el, err := element.ElementX(field.Selector)
if err != nil {
return nil, fmt.Errorf("element not found for selector: %s", field.Selector)
}
text, err := el.Text()
if err != nil {
return nil, fmt.Errorf("failed to get text from element: %s", field.Selector)
}
matches := regexp.MustCompile(field.Pattern).FindStringSubmatch(text)
if len(matches) > 1 {
id = strings.Join(matches[1:], "/")
} else {
return nil, fmt.Errorf("failed to extract id from element using pattern: %s", field.Pattern)
}
default:
return nil, fmt.Errorf("unsupported from: %s", field.From)
}
return id, nil
}
if strings.HasPrefix(field.Name, "_time") {
// extract time from url or element
var time string
switch field.From {
case FromURL:
url := element.Page().MustInfo().URL
matches := regexp.MustCompile(field.Pattern).FindStringSubmatch(url)
if len(matches) > 1 {
time = strings.Join(matches[1:], "/")
} else {
return nil, fmt.Errorf("failed to extract time from URL using pattern: %s", field.Pattern)
}
case FromElement:
el, err := element.ElementX(field.Selector)
if err != nil {
return nil, fmt.Errorf("element not found for selector: %s", field.Selector)
}
text, err := el.Text()
if err != nil {
return nil, fmt.Errorf("failed to get text from element: %s", field.Selector)
}
matches := regexp.MustCompile(field.Pattern).FindStringSubmatch(text)
if len(matches) > 1 {
time = strings.Join(matches[1:], "/")
} else {
return nil, fmt.Errorf("failed to extract time from element using pattern: %s", field.Pattern)
}
default:
return nil, fmt.Errorf("unsupported from: %s", field.From)
}
return time, nil
}
switch field.Type {
case "text":
el, err := element.ElementX(field.Selector)
if err != nil {
return "", fmt.Errorf("element not found for selector: %s", field.Selector)
}
return el.Text()
case "attribute":
el, err := element.ElementX(field.Selector)
if err != nil {
return "", fmt.Errorf("element not found for selector: %s", field.Selector)
}
return el.Attribute(field.Attribute)
case "nested":
nestedElement, err := element.ElementX(field.Selector)
if err != nil {
return nil, fmt.Errorf("nested element not found for selector: %s", field.Selector)
}
nestedItem := make(ExtractedItem)
for _, nestedField := range field.Fields {
nestedValue, err := e.extractField(nestedElement, nestedField)
if err != nil {
continue
}
nestedItem[nestedField.Name] = nestedValue
}
if len(nestedItem) > 0 {
return nestedItem, nil
}
return nil, fmt.Errorf("all nested fields failed to extract")
case "list":
elements, err := element.ElementsX(field.Selector)
if err != nil {
return nil, fmt.Errorf("elements not found for selector: %s", field.Selector)
}
// 检查是否只有一个子字段
if len(field.Fields) == 1 && field.Fields[0].Type == "text" && field.Fields[0].Selector == "." {
// 简化输出为字符串数组
var items []string
for _, el := range elements {
value, err := e.extractField(el, field.Fields[0])
if err != nil {
continue
}
if str, ok := value.(string); ok {
items = append(items, str)
}
}
return items, nil
}
// 原有的对象数组处理逻辑
var items []map[string]interface{}
for _, el := range elements {
item := make(map[string]interface{})
for _, subField := range field.Fields {
value, err := e.extractField(el, subField)
if err != nil {
continue
}
item[subField.Name] = value
}
items = append(items, item)
}
return items, nil
default:
return nil, fmt.Errorf("unsupported field type: %s", field.Type)
}
}
func extractExternalID(item map[string]interface{}) (string, bool) {
idItem, ok := item["_id"]
if !ok {
return "", false
}
switch idValue := idItem.(type) {
case string:
return idValue, true
case ExtractedItem:
type idField struct {
FieldK string
FieldV string
}
idFields := []idField{}
for idk, idv := range idValue {
if !strings.HasPrefix(idk, "_id") {
continue
}
if fieldV, ok := idv.(string); ok {
idFields = append(idFields, idField{
FieldK: idk,
FieldV: fieldV,
})
}
}
sort.Slice(idFields, func(i, j int) bool {
return idFields[i].FieldK < idFields[j].FieldK
})
idParts := []string{}
for _, idField := range idFields {
idParts = append(idParts, idField.FieldV)
}
return strings.Join(idParts, "_"), true
}
return "", false
}
func extractExternalTime(item map[string]interface{}) (time.Time, bool) {
timeItem, ok := item["_time"]
if !ok {
return time.Time{}, false
}
loc, err := time.LoadLocation("Asia/Hong_Kong")
if err != nil {
return time.Time{}, false
}
switch timeValue := timeItem.(type) {
case string:
if t, err := time.ParseInLocation("2006/01/02", timeValue, loc); err == nil {
return t, true
}
case ExtractedItem:
type timeField struct {
FieldK string
FieldV string
}
timeFields := []timeField{}
for timek, timev := range timeValue {
if !strings.HasPrefix(timek, "_time") {
continue
}
if fieldV, ok := timev.(string); ok {
timeFields = append(timeFields, timeField{
FieldK: timek,
FieldV: fieldV,
})
}
}
sort.Slice(timeFields, func(i, j int) bool {
return timeFields[i].FieldK < timeFields[j].FieldK
})
timeParts := []string{}
for _, timeField := range timeFields {
timeParts = append(timeParts, timeField.FieldV)
}
if t, err := time.ParseInLocation("2006/01/02", strings.Join(timeParts, "/"), loc); err == nil {
return t, true
}
}
return time.Time{}, false
}