-
Notifications
You must be signed in to change notification settings - Fork 3
/
browser.go
204 lines (170 loc) · 4.55 KB
/
browser.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
package gofofa
import (
"context"
"errors"
"fmt"
"github.com/go-rod/rod"
"github.com/go-rod/rod/lib/devices"
"github.com/go-rod/rod/lib/launcher"
"github.com/go-rod/rod/lib/proto"
"golang.org/x/net/html"
"log"
"strings"
"time"
)
type WorkerBrowser struct {
Url string
}
func NewWorkerBrowser(url string) *WorkerBrowser {
return &WorkerBrowser{
Url: url,
}
}
func (wp *WorkerBrowser) Run() (response map[string]interface{}, err error) {
defer func() {
if r := recover(); r != nil {
err = fmt.Errorf("panic occurred: %v", r)
log.Println("browser render error:", r, "Url:", wp.Url)
}
}()
if wp.Url == "" {
return nil, errors.New("url is empty")
}
body, err := wp.renderScan(wp.Url)
if err != nil {
return nil, errors.New("browser render error" + err.Error())
}
response = make(map[string]interface{})
response["url"] = wp.Url
if !strings.Contains(body, "<title>") {
response["body"] = body
return response, nil
}
title := strings.TrimSpace(wp.ParseHTML(body, "title"))
title = wp.removeExtraSpaces(title)
response["body"] = body
response["title"] = title
return response, nil
}
func (wp *WorkerBrowser) ParseHTML(htmlStr string, tag string) string {
doc, err := html.Parse(strings.NewReader(htmlStr))
if err != nil {
log.Println("parsing HTML error", err)
return ""
}
return wp.findNodeText(doc, tag)
}
func (wp *WorkerBrowser) removeExtraSpaces(input string) string {
// 将空白字符都转换成空格
input = strings.ReplaceAll(input, "\n", ` `)
input = strings.ReplaceAll(input, "\t", ` `)
input = strings.ReplaceAll(input, "\r", ` `)
var builder strings.Builder
wasSpace := false
// 遍历输入字符串的每个字符
for _, char := range input {
if char == ' ' {
if wasSpace {
continue
}
wasSpace = true
} else {
wasSpace = false
}
builder.WriteRune(char)
}
return builder.String()
}
func (wp *WorkerBrowser) findNodeText(n *html.Node, tag string) string {
if n.Type == html.ElementNode && n.Data == tag {
if n.FirstChild != nil && n.FirstChild.Type == html.TextNode {
return n.FirstChild.Data
}
}
for c := n.FirstChild; c != nil; c = c.NextSibling {
result := wp.findNodeText(c, tag)
if result != "" {
return result
}
}
return ""
}
func (wp *WorkerBrowser) renderScan(url string) (string, error) {
const maxRetries = 3
const retryDelay = 5 * time.Second
var lastErr error
for attempt := 1; attempt <= maxRetries; attempt++ {
bodyHTML, err := func() (string, error) {
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
dev := devices.Device{
Title: "Laptop with MDPI screen",
Capabilities: []string{},
UserAgent: `Mozilla/5.0 (Windows NT 6.3; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/73.0.3683.103 Safari/537.36`,
AcceptLanguage: "zh-CN,zh;q=0.9,en;q=0.8",
Screen: devices.Screen{
DevicePixelRatio: 1,
Horizontal: devices.ScreenSize{
Width: 1280,
Height: 800,
},
Vertical: devices.ScreenSize{
Width: 800,
Height: 1280,
},
},
}
l := launcher.New().
Headless(true).
Devtools(true)
defer l.Cleanup()
l.Set("disable-web-security")
l.Set("allow-running-insecure-content")
l.Set("--ignore-certificate-errors")
l.Set("disable-notifications", "true")
lurl := l.MustLaunch()
b := rod.New().ControlURL(lurl).
DefaultDevice(dev).
Timeout(10 * time.Second).
Trace(false).
MustConnect()
defer b.MustClose()
page := b.MustPage().Context(ctx)
defer page.MustClose()
// 启动协程监听浏览器弹窗事件
go func() {
page.EachEvent(func(e *proto.PageJavascriptDialogOpening) {
_ = proto.PageHandleJavaScriptDialog{Accept: false, PromptText: ""}.Call(page)
})()
select {
case <-ctx.Done():
return
}
}()
if err := page.Navigate(url); err != nil {
return "", fmt.Errorf("navigation error: %v", err)
}
if err := page.WaitLoad(); err != nil {
return "", fmt.Errorf("page load error: %v", err)
}
time.Sleep(3 * time.Second)
// 获取页面的 HTML 内容
body, err := page.Element("html")
if err != nil {
return "", fmt.Errorf("not find html element: %v", err)
}
bodyHtml, err := body.HTML()
if err != nil {
return "", fmt.Errorf("failed to get html content: %v", err)
}
return bodyHtml, nil
}()
if err == nil && bodyHTML != "" {
return bodyHTML, nil
}
lastErr = err
log.Printf("Attempt %d failed: %v", attempt, lastErr)
time.Sleep(retryDelay)
}
return "", fmt.Errorf("all attempts failed: %v", lastErr)
}