Skip to content

使用多个收集器

如果任务十分复杂或具有不同类型的子任务,建议将多个收集器用于一个爬虫作业。一个很好的例子是coursera course scraper,其中使用了两个收集器,一个解析列表视图并处理分页,另一个收集课程详细信息。


INFO

使用收集器。调试中的ID以区分不同的收集器

1.克隆收集器

如果收集器具有类似的配置,则可以使用收集器的 Clone() 方法。 Clone() 复制具有相同配置但没有关联回调的收集器。

go
c := colly.NewCollector(
	colly.UserAgent("myUserAgent"),
	colly.AllowedDomains("foo.com", "bar.com"),
)
// Custom User-Agent and allowed domains are cloned to c2
c2 := c.Clone()

在收集器之间传递自定义数据

使用收集器的 Request() 函数能够与其他收集器共享上下文对象 例如:

go
c.OnResponse(func(r *colly.Response) {
	r.Ctx.Put(r.Headers.Get("Custom-Header"))
	c2.Request("GET", "https://foo.com/", nil, r.Ctx, nil)
})