Colly是一个高度可定制的抓取框架。它有合理的默认值,并提供了大量的选项来更改它们。网络
收集器属性的完整列表能够在这里找到。初始化收集器的推荐方法是使用 colly.NewCollector(options...)。框架
建立一个具备默认设置的收集器:dom
c1 := colly.NewCollector()
建立另外一个收集器,并更改用户代理和url从新操做:url
c2 := colly.NewCollector( colly.UserAgent("xy"), colly.AllowURLRevisit(), )
或者代理
c2 := colly.NewCollector() c2.UserAgent = "xy" c2.AllowURLRevisit = true
经过覆盖收集器的属性,能够在抓取做业的任什么时候候更改配置。code
const letterBytes = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ" func RandomString() string { b := make([]byte, rand.Intn(10)+10) for i := range b { b[i] = letterBytes[rand.Intn(len(letterBytes))] } return string(b) } c := colly.NewCollector() c.OnRequest(func(r *colly.Request) { r.Headers.Set("User-Agent", RandomString()) })
收集器的默认配置能够经过环境变量更改。这容许咱们在不从新编译的状况下微调收集器。环境解析是收集器初始化的最后一步,所以初始化以后的每一个配置更改都会覆盖从环境中解析的配置。blog
ALLOWED_DOMAINS
(用逗号分隔的域列表)CACHE_DIR
(string)DETECT_CHARSET
(y/n)DISABLE_COOKIES
(y/n)DISALLOWED_DOMAINS
(用逗号分隔的域列表)IGNORE_ROBOTSTXT
(y/n)MAX_BODY_SIZE
(int)MAX_DEPTH
(int - 0表示无穷大)PARSE_HTTP_ERROR_RESPONSE
(y/n)USER_AGENT
(string)Colly使用Golang的默认http客户端做为网络层。能够经过更改默认的HTTP往返器调整HTTP选项。ip
c := colly.NewCollector() c.WithTransport(&http.Transport{ Proxy: http.ProxyFromEnvironment, DialContext: (&net.Dialer{ Timeout: 30 * time.Second, KeepAlive: 30 * time.Second, DualStack: true, }).DialContext, MaxIdleConns: 100, IdleConnTimeout: 90 * time.Second, TLSHandshakeTimeout: 10 * time.Second, ExpectContinueTimeout: 1 * time.Second, }