/
crawler.go
68 lines (58 loc) · 1.86 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
package crawler
import (
"github.com/wcong/ants-go/ants/http"
base_spider "github.com/wcong/ants-go/ants/spiders"
"github.com/wcong/ants-go/ants/util"
"github.com/wcong/ants-go/spiders"
)
// crawler
type Crawler struct {
SpiderMap map[string]*base_spider.Spider //contains all spiders
RequestQuene *RequestQuene //all waiting request
ResponseQuene *ResponseQuene //all waiting response for scrape
Downloader *Downloader //download tools
Scraper *Scraper //scrape tools
}
// resultQuene is for reporter,make sure it is the same ppointer
func NewCrawler(resultQuene *ResultQuene, settings *util.Settings) *Crawler {
requestQuene := NewRequestQuene()
responseQuene := NewResponseQuene()
spiderMap := spiders.LoadAllSpiders()
downloader := NewDownloader(requestQuene, responseQuene, settings.DownloadInterval)
scraper := NewScraper(resultQuene, responseQuene, spiderMap)
crawler := &Crawler{spiderMap, requestQuene, responseQuene, downloader, scraper}
return crawler
}
func (this *Crawler) GetStartRequest(spiderName string) []*http.Request {
spider := this.SpiderMap[spiderName]
startRequests := spider.MakeStartRequests()
return startRequests
}
func (this *Crawler) StartSpider(spiderName string) {
beforeMethod := this.SpiderMap[spiderName].BeforeMethod
if beforeMethod != nil {
beforeMethod()
}
}
func (this *Crawler) CloseSpider(spiderName string) {
afterMethod := this.SpiderMap[spiderName].AfterMethod
if afterMethod != nil {
afterMethod()
}
}
func (this *Crawler) Start() {
go this.Downloader.Start()
go this.Scraper.Start()
}
func (this *Crawler) Pause() {
this.Downloader.Pause()
this.Scraper.Pause()
}
func (this *Crawler) UnPause() {
this.Downloader.UnPause()
this.Scraper.UnPause()
}
func (this *Crawler) Stop() {
this.Downloader.Stop()
this.Scraper.Stop()
}