-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathscraper.go
More file actions
190 lines (166 loc) · 3.99 KB
/
scraper.go
File metadata and controls
190 lines (166 loc) · 3.99 KB
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
package main
import (
"fmt"
"net/http"
"net/url"
"os"
"strings"
"sync"
"time"
"golang.org/x/net/html"
)
type Result struct {
URL string
Content string
Error error
}
func main() {
if len(os.Args) < 2 {
fmt.Println("Usage: go run scraper.go <domain>")
return
}
domain := os.Args[1]
baseURL := domain
if !strings.HasPrefix(baseURL, "http") {
baseURL = "https://" + domain
}
maxPages := 15
concurrency := 5
timeout := 10 * time.Second
visited := &sync.Map{}
results := make(chan Result, maxPages)
queue := make(chan string, maxPages*2)
// Keywords for relevant subdomains and paths
relevantKeywords := []string{"security", "privacy", "compliance", "trust", "legal", "investors", "governance", "certification", "faq"}
// Seed the queue
queue <- baseURL
visited.Store(baseURL, true)
// Try subdomains
for _, kw := range []string{"trust", "security", "compliance", "docs"} {
sd := fmt.Sprintf("https://%s.%s", kw, domain)
queue <- sd
visited.Store(sd, true)
}
var wg sync.WaitGroup
crawlerMutex := sync.Mutex{}
// Start crawlers
for i := 0; i < concurrency; i++ {
wg.Add(1)
go func() {
defer wg.Done()
for {
crawlerMutex.Lock()
if len(results) >= maxPages {
crawlerMutex.Unlock()
return
}
crawlerMutex.Unlock()
select {
case targetURL := <-queue:
content, links, err := scrape(targetURL, timeout)
results <- Result{URL: targetURL, Content: content, Error: err}
if err == nil {
for _, link := range links {
if isRelevant(link, domain, relevantKeywords) {
if _, loaded := visited.LoadOrStore(link, true); !loaded {
select {
case queue <- link:
default:
}
}
}
}
}
case <-time.After(2 * time.Second):
return
}
}
}()
}
go func() {
wg.Wait()
close(results)
}()
// Collect results
var finalContent strings.Builder
count := 0
for res := range results {
if res.Error == nil && len(res.Content) > 200 {
finalContent.WriteString(fmt.Sprintf("\n--- SOURCE: %s ---\n%s\n", res.URL, res.Content))
count++
}
if count >= maxPages {
break
}
}
fmt.Print(finalContent.String())
}
func scrape(targetURL string, timeout time.Duration) (string, []string, error) {
client := &http.Client{Timeout: timeout}
resp, err := client.Get(targetURL)
if err != nil {
return "", nil, err
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return "", nil, fmt.Errorf("bad status: %d", resp.StatusCode)
}
doc, err := html.Parse(resp.Body)
if err != nil {
return "", nil, err
}
var content strings.Builder
var links []string
var f func(*html.Node)
f = func(n *html.Node) {
if n.Type == html.ElementNode && n.Data == "a" {
for _, a := range n.Attr {
if a.Key == "href" {
abs := absoluteURL(targetURL, a.Val)
if abs != "" {
links = append(links, abs)
}
}
}
}
if n.Type == html.TextNode {
parent := n.Parent
if parent.Data != "script" && parent.Data != "style" && parent.Data != "nav" && parent.Data != "footer" {
content.WriteString(strings.TrimSpace(n.Data) + " ")
}
}
for c := n.FirstChild; c != nil; c = c.NextSibling {
f(c)
}
}
f(doc)
return strings.Join(strings.Fields(content.String()), " "), links, nil
}
func absoluteURL(base, href string) string {
u, err := url.Parse(href)
if err != nil {
return ""
}
b, err := url.Parse(base)
if err != nil {
return ""
}
return b.ResolveReference(u).String()
}
func isRelevant(link, domain string, keywords []string) bool {
u, err := url.Parse(link)
if err != nil {
return false
}
// Stay on domain (or subdomains)
if !strings.Contains(u.Host, domain) {
return false
}
lowURL := strings.ToLower(link)
for _, kw := range keywords {
if strings.Contains(lowURL, kw) {
return true
}
}
return false
}