/
crawler.go
220 lines (194 loc) · 5.83 KB
/
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
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
//
package main
/*
Packages must be imported:
"core/common/page"
"core/spider"
Pckages may be imported:
"core/pipeline": scawler result persistent;
"github.com/PuerkitoBio/goquery": html dom parser.
*/
import (
"flag"
"fmt"
"log"
"net/url"
"regexp"
"github.com/PuerkitoBio/goquery"
"github.com/henrylee2cn/pholcus/common/mlog"
"github.com/hu17889/go_spider/core/common/page"
"github.com/hu17889/go_spider/core/pipeline"
"github.com/hu17889/go_spider/core/spider"
"github.com/plutoshe/webCrawler/repetition"
"github.com/plutoshe/webCrawler/storage"
"github.com/plutoshe/webCrawler/urlstore"
"gopkg.in/mgo.v2"
"gopkg.in/redis.v3"
)
var (
exitChan chan struct{}
getURL chan string
releaseSlot chan int
collection *mgo.Collection
rep repetition.RepetitionJudgement
urlstr urlstore.URLCrawlerStore
base = "www.dazhongdainping.com"
// spider configuration
threadNum = flag.Int("threadNum", 4, "Specify the thread number to crawl. The default value is 4.")
// redis configuration
redisURL = flag.String("redisURL", "localhost:6379", "Specify the url address of redis")
redisPWD = flag.String("redisPWD", "", "Specify the password linking redis")
redisDB = flag.Int64("redisDB", 0, "Set redis db num")
// mongodb configuration
databaseURL = flag.String("dbURL", storage.MONGODB_URL, "Identify the linked db adress")
databaseName = flag.String("dbname", storage.MONGODB_DB, "Denote the database name of mongodb")
databaseAuth = flag.Bool("dbauth", false, "Denote whether link datatbase by authentication or not")
databaseUser = flag.String("dbuser", storage.MONGODB_USER, "Denote the user name of db")
databasePwd = flag.String("dbpwd", storage.MONGODB_PWD, "Regarding the user name, denote corresponding password")
collectionName = flag.String("collection", storage.MONGODB_COLLECTION, "Denote the coolection name to operate")
)
type MyPageProcesser struct {
}
func NewMyPageProcesser() *MyPageProcesser {
return &MyPageProcesser{}
}
func checkMatchPattern(base, href string) bool {
// inDomain := regexp.MustCompile("dianping\\.com")
inDomain := regexp.MustCompile("dianping\\.com(\\/[^\\/\n]+){2,2}$")
if inDomain.MatchString(href) {
// fmt.Println("in ", href)
return true
}
return false
}
// Parse html dom here and record the parse result that we want to Page.
// Package goquery (http://godoc.org/github.com/PuerkitoBio/goquery) is used to parse html.
func (this *MyPageProcesser) Process(p *page.Page) {
if !p.IsSucc() {
println(p.Errormsg())
return
}
query := p.GetHtmlParser()
currentUrl := p.GetRequest().GetUrl()
var urls []string
query.Find("a").Each(func(i int, s *goquery.Selection) {
href, _ := s.Attr("href")
urlHref, err := url.Parse(href)
if err != nil {
mlog.LogInst().LogError(err.Error())
return
}
if !urlHref.IsAbs() {
href = currentUrl + href
}
// Temporarily check in crawler.go, it will be implemented in pattern package.
if checkMatchPattern(base, href) {
visited, _ := rep.CheckIfVisited(href)
if !visited {
rep.VisitedNewNode(href)
// urls = append(urls, href)
urlstr.UploadURL(href)
}
}
})
// store content to db
fmt.Printf("====store & commit : %s====\n\n\n", currentUrl)
content, _ := query.Html()
// content := ""
storage.StoreInsert(collection, storage.StoreFormat{currentUrl, content})
urlstr.CommitURL(currentUrl)
releaseSlot <- 1
url := GetOneURL()
if url != "" {
urls = append(urls, url)
}
p.AddTargetRequests(urls, "html")
}
func (this *MyPageProcesser) Finish() {
// fmt.Printf("TODO:before end spider \r\n")
}
func distributeURL(threadNum int, urlstr urlstore.URLCrawlerStore) {
var remain int = 0
for {
select {
case <-releaseSlot:
remain++
oldRemain := remain
for i := 0; i < oldRemain; i++ {
url, err := urlstr.GetOneNeedCrawlerURL()
if err != nil {
log.Printf("Distribute URL error, error Msg = \"%v\"\n", err)
continue
}
if url == "" {
break
}
remain--
getURL <- url
}
if oldRemain == threadNum && remain == threadNum {
close(exitChan)
break
}
}
}
}
func GetOneURL() string {
for {
select {
case URL := <-getURL:
return URL
case <-exitChan:
return ""
}
}
}
func main() {
flag.Parse()
// chan init
exitChan = make(chan struct{})
getURL = make(chan string, *threadNum)
releaseSlot = make(chan int, *threadNum)
// repetition and urlstor initialization
c := redis.NewClient(&redis.Options{
Addr: *redisURL,
Password: *redisPWD,
DB: *redisDB,
})
rep = repetition.RepetitionJudgement{}
err := rep.InitializeVisited(c, "repetition")
if err != nil {
log.Fatal("redis error, ", err)
}
urlstr = urlstore.URLCrawlerStore{}
_, err = urlstr.InitialURLsStore(c, "colNeedCrawl", "colNeedCommit", "colNeedCrawl", "colNeedCommit")
visited, _ := rep.CheckIfVisited("http://www.dianping.com/")
if !visited {
rep.VisitedNewNode("http://www.dianping.com/")
urlstr.UploadURL("http://www.dianping.com/")
}
if err != nil {
log.Fatal("urlstore initialzation error, ", err)
}
// db initilization
dbSession, err := storage.Link2Db(*databaseURL)
defer dbSession.Close()
if err != nil {
log.Fatal("mongodb error, ", err)
}
collection = storage.Link2Collection(dbSession, *databaseName, *databaseUser, *databasePwd, *collectionName, *databaseAuth)
go distributeURL(*threadNum, urlstr)
// url initilziation
for i := 0; i < *threadNum; i++ {
releaseSlot <- 1
}
rootURL := GetOneURL()
// Spider input:
// PageProcesser ;
// Task name used in Pipeline for record;
spider.NewSpider(NewMyPageProcesser(), "TaskName").
AddUrl(rootURL, "html"). // Start url, html is the responce type ("html" or "json" or "jsonp" or "text")
AddPipeline(pipeline.NewPipelineConsole()). // Print result on screen
SetThreadnum((uint)(*threadNum)). // Crawl request by three Coroutines
Run()
}