-
Notifications
You must be signed in to change notification settings - Fork 66
/
html.go
72 lines (59 loc) · 1.47 KB
/
html.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
package queryUtils
import (
"fmt"
"github.com/aaronchen2k/deeptest/internal/pkg/consts"
"github.com/antchfx/htmlquery"
"github.com/antchfx/xpath"
"strings"
)
func HtmlQuery(content string, expression string) (result string) {
defer func() {
if err := recover(); err != nil {
fmt.Println(err)
}
}()
doc, err := htmlquery.Parse(strings.NewReader(content))
if err != nil {
result = consts.ContentErr
return
}
if isEvaluate(expression) {
expr, _ := xpath.Compile(expression)
float := expr.Evaluate(htmlquery.CreateXPathNavigator(doc))
result = fmt.Sprintf("%v", float)
return
}
expression, propName := GetExpressionForXpathSelector(expression)
elem, err := htmlquery.Query(doc, expression)
if err != nil || elem == nil {
result = consts.ExtractorErr
return
}
obj := ""
if propName != "" {
obj = htmlquery.SelectAttr(elem, propName)
} else {
obj = htmlquery.InnerText(elem)
if obj == "" {
obj = htmlquery.OutputHTML(elem, true)
}
//if elem.FirstChild != nil {
// obj = htmlquery.OutputHTML(elem, true)
//} else {
// obj = htmlquery.InnerText(elem)
//}
}
result = fmt.Sprintf("%v", obj)
return
}
func GetExpressionForXpathSelector(str string) (expression, propName string) {
arr := strings.Split(str, "/")
lastSection := arr[len(arr)-1]
if strings.Index(lastSection, "@") == 0 {
propName = strings.TrimPrefix(lastSection, "@")
expression = strings.TrimSuffix(str, "/"+lastSection)
} else {
expression = str
}
return
}