-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgo_crawler.go
111 lines (92 loc) · 1.87 KB
/
go_crawler.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
package main
import (
"fmt"
http "net/http"
"os"
"strings"
html "golang.org/x/net/html"
)
func getHref(t html.Token) (ok bool, href string) {
for _, a := range t.Attr {
if a.Key == "href" {
href = a.Val
ok = true
}
}
return
}
// crawl with channel
func crawl(url string, ch chan string, chFinished chan bool) {
/*
param url: the url to crawl for information
param ch: the channel to save extracted shared urls
param chFinished: the channel to save status
*/
// publish the urls if finds to shared channel
resp, err := http.Get(url)
defer func() {
chFinished <- true
}()
if err != nil {
return
}
b := resp.Body
defer b.Close()
// parse the response
z := html.NewTokenizer(b)
for {
tt := z.Next()
// switch used with concrete types
switch {
case tt == html.ErrorToken:
return
case tt == html.StartTagToken:
t := z.Token()
isAnchor := t.Data == "a"
if !isAnchor {
continue
}
ok, url := getHref(t)
if !ok {
continue
}
// make sure the url begins with http**
hasProto := strings.Index(url, "http") == 0
if hasProto {
// second channel for communication status
ch <- url
}
}
}
}
// example of cocurrency
func main() {
foundUrls := make(map[string]bool)
seedUrls := os.Args[1:]
// Channels
chUrls := make(chan string)
chFinished := make(chan bool)
// multiple crawl process
for _, url := range seedUrls {
// cocurrecy scraping
go crawl(url, chUrls, chFinished)
}
// subscribe to both channels
for c := 0; c < len(seedUrls); {
// select is used with channels
select {
case url := <-chUrls:
foundUrls[url] = true
case <-chFinished:
// increase c if there is one url finished
c++
}
}
// print out the results
fmt.Println("\nFound", len(foundUrls), "unique urls: \n")
for url, _ := range foundUrls {
fmt.Println(" - " + url)
}
close(chUrls)
close(chFinished)
}