-
Notifications
You must be signed in to change notification settings - Fork 0
/
static_extractor.go
337 lines (298 loc) · 8.84 KB
/
static_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
package extractor
import (
"fmt"
"regexp"
"strings"
"time"
"github.com/antchfx/htmlquery"
"github.com/crawlerclub/httpcache"
"golang.org/x/net/html"
)
type StaticExtractor struct {
Config ExtractorConfig
}
func NewStaticExtractor(config ExtractorConfig) *StaticExtractor {
return &StaticExtractor{Config: config}
}
func (e *StaticExtractor) Extract(url string) (*ExtractionResult, error) {
client := httpcache.GetClient()
htmlContent, finalURL, err := client.GetWithFinalURL(url)
if err != nil {
return nil, fmt.Errorf("failed to read response body: %v", err)
}
needDelete := true
result := &ExtractionResult{
SchemaResults: make(map[string]SchemaResult),
Errors: make([]ExtractionError, 0),
FinalURL: finalURL,
}
doc, err := htmlquery.Parse(strings.NewReader(string(htmlContent)))
if err != nil {
return nil, fmt.Errorf("failed to parse HTML: %v", err)
}
// 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 := htmlquery.QueryAll(doc, 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),
})
continue
}
for _, element := range elements {
item, errs := e.extractItemWithSchema(element, schema, url, doc)
if len(errs) > 0 {
result.Errors = append(result.Errors, errs...)
}
if item != nil {
needDelete = false
// 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
}
if needDelete {
client.DeleteURL(url)
}
return result, nil
}
func (e *StaticExtractor) extractItemWithSchema(element *html.Node, schema Schema, url string, doc *html.Node) (ExtractedItem, []ExtractionError) {
item := make(ExtractedItem)
var errors []ExtractionError
for _, field := range schema.Fields {
value, err := e.extractField(element, field, url, doc)
if err != nil {
errors = append(errors, ExtractionError{
Field: field.Name,
Message: err.Error(),
})
continue
}
item[field.Name] = value
}
return item, errors
}
func (e *StaticExtractor) evaluateCount(countXPath string, element *html.Node, doc *html.Node) (int, error) {
if !isValidXPath(countXPath) {
return 0, fmt.Errorf("invalid XPath expression: %s", countXPath)
}
if strings.HasPrefix(countXPath, "//") {
nodes := htmlquery.Find(doc, countXPath)
return len(nodes), nil
} else {
nodes := htmlquery.Find(element, countXPath)
return len(nodes), nil
}
}
func (e *StaticExtractor) extractField(element *html.Node, field Field, url string, doc *html.Node) (interface{}, error) {
// Helper function to handle XPath queries
queryElement := func(selector string, contextNode *html.Node) (*html.Node, error) {
if strings.HasPrefix(selector, "//") {
return htmlquery.FindOne(doc, selector), nil
}
return htmlquery.FindOne(contextNode, selector), nil
}
queryElements := func(selector string, contextNode *html.Node) ([]*html.Node, error) {
if strings.HasPrefix(selector, "//") {
return htmlquery.Find(doc, selector), nil
}
return htmlquery.Find(contextNode, selector), nil
}
// Helper function to process count expressions in selector
processCountExpression := func(selector string) (string, error) {
for strings.Contains(selector, "count(") {
start := strings.Index(selector, "count(")
if start == -1 {
break
}
bracketCount := 1
end := start + 6
for end < len(selector) && bracketCount > 0 {
if selector[end] == '(' {
bracketCount++
} else if selector[end] == ')' {
bracketCount--
}
end++
}
if bracketCount != 0 {
return "", fmt.Errorf("unmatched brackets in count expression")
}
countXPath := selector[start+6 : end-1]
count, err := e.evaluateCount(countXPath, element, doc)
if err != nil {
return "", err
}
selector = selector[:start] + fmt.Sprintf("%d", count) + selector[end:]
}
return selector, nil
}
if strings.HasPrefix(field.Name, "_id") || strings.HasPrefix(field.Name, "_time") {
if field.Type == "nested" {
// Nested ID handling remains unchanged
nestedElement := element
nestedItem := make(ExtractedItem)
for _, nestedField := range field.Fields {
nestedValue, err := e.extractField(nestedElement, nestedField, url, doc)
if err != nil {
continue
}
nestedItem[nestedField.Name] = nestedValue
}
if len(nestedItem) > 0 {
return nestedItem, nil
}
}
switch field.From {
case FromURL:
matches := regexp.MustCompile(field.Pattern).FindStringSubmatch(url)
if len(matches) > 1 {
return strings.Join(matches[1:], "/"), nil
}
return nil, fmt.Errorf("failed to extract from URL using pattern: %s", field.Pattern)
case FromElement:
if strings.Contains(field.Selector, "count(") {
processedSelector, err := processCountExpression(field.Selector)
if err != nil {
return nil, err
}
field.Selector = processedSelector
}
el, _ := queryElement(field.Selector, element)
if el == nil {
return nil, fmt.Errorf("element not found for selector: %s", field.Selector)
}
text := htmlquery.InnerText(el)
matches := regexp.MustCompile(field.Pattern).FindStringSubmatch(text)
if len(matches) > 1 {
return strings.Join(matches[1:], "/"), nil
}
return nil, fmt.Errorf("failed to extract from element using pattern: %s", field.Pattern)
default:
return nil, fmt.Errorf("unsupported from: %s", field.From)
}
}
switch field.Type {
case "text":
if strings.Contains(field.Selector, "count(") {
processedSelector, err := processCountExpression(field.Selector)
if err != nil {
return "", err
}
field.Selector = processedSelector
}
el, _ := queryElement(field.Selector, element)
if el == nil {
return "", fmt.Errorf("element not found for selector: %s", field.Selector)
}
text := htmlquery.InnerText(el)
text = regexp.MustCompile(`[ \t]+`).ReplaceAllString(text, " ")
lines := strings.Split(text, "\n")
var nonEmptyLines []string
for _, line := range lines {
trimmed := strings.TrimSpace(line)
if trimmed != "" {
nonEmptyLines = append(nonEmptyLines, trimmed)
}
}
return strings.Join(nonEmptyLines, "\n"), nil
case "attribute":
el, _ := queryElement(field.Selector, element)
if el == nil {
return "", fmt.Errorf("element not found for selector: %s", field.Selector)
}
for _, attr := range el.Attr {
if attr.Key == field.Attribute {
return attr.Val, nil
}
}
return "", fmt.Errorf("attribute %s not found", field.Attribute)
case "nested":
nestedElement, _ := queryElement(field.Selector, element)
if nestedElement == 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, url, doc)
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, _ := queryElements(field.Selector, element)
if len(elements) == 0 {
return nil, fmt.Errorf("elements not found for selector: %s", field.Selector)
}
// Check for single text field case
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], url, doc)
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, url, doc)
if err != nil {
continue
}
item[subField.Name] = value
}
if len(item) > 0 {
items = append(items, item)
}
}
return items, nil
default:
return nil, fmt.Errorf("unsupported field type: %s", field.Type)
}
}
func isValidXPath(xpath string) bool {
bracketCount := 0
for _, c := range xpath {
if c == '(' {
bracketCount++
} else if c == ')' {
bracketCount--
}
if bracketCount < 0 {
return false
}
}
return bracketCount == 0
}