-
Notifications
You must be signed in to change notification settings - Fork 0
/
colly.go
65 lines (54 loc) · 1.77 KB
/
colly.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
package main
import (
"fmt"
"github.com/gocolly/colly"
)
func main() {
// NewCollector(options ...func(*Collector)) *Collector
// 声明初始化NewCollector对象时可以指定Agent,连接递归深度,URL过滤以及domain限制等
c := colly.NewCollector(
//colly.AllowedDomains("news.baidu.com"),
colly.UserAgent("Opera/9.80 (Windows NT 6.1; U; zh-cn) Presto/2.9.168 Version/11.50"))
// 发出请求时附的回调
c.OnRequest(func(r *colly.Request) {
// Request头部设定
r.Headers.Set("Host", "baidu.com")
r.Headers.Set("Connection", "keep-alive")
r.Headers.Set("Accept", "*/*")
r.Headers.Set("Origin", "")
r.Headers.Set("Referer", "http://www.baidu.com")
r.Headers.Set("Accept-Encoding", "gzip, deflate")
r.Headers.Set("Accept-Language", "zh-CN, zh;q=0.9")
fmt.Println("Visiting", r.URL)
})
// 对响应的HTML元素处理
c.OnHTML("title", func(e *colly.HTMLElement) {
//e.Request.Visit(e.Attr("href"))
fmt.Println("title:", e.Text)
})
c.OnHTML("body", func(e *colly.HTMLElement) {
// <div class="hotnews" alog-group="focustop-hotnews"> 下所有的a解析
e.ForEach(".hotnews a", func(i int, el *colly.HTMLElement) {
band := el.Attr("href")
title := el.Text
fmt.Printf("新闻 %d : %s - %s\n", i, title, band)
// e.Request.Visit(band)
})
})
// 发现并访问下一个连接
//c.OnHTML(`.next a[href]`, func(e *colly.HTMLElement) {
// e.Request.Visit(e.Attr("href"))
//})
// extract status code
c.OnResponse(func(r *colly.Response) {
fmt.Println("response received", r.StatusCode)
// 设置context
// fmt.Println(r.Ctx.Get("url"))
})
// 对visit的线程数做限制,visit可以同时运行多个
c.Limit(&colly.LimitRule{
Parallelism: 2,
//Delay: 5 * time.Second,
})
c.Visit("http://news.baidu.com")
}