Skip to content

并行


go
package main

import (
	"fmt"
	"github.com/gocolly/colly"
)

func main() {
	// 实例化默认 collector
	c := colly.NewCollector(
		// 最大深度为2,所以只会爬取目标网页,以及这些网页中包含的链接页面
		colly.MaxDepth(2),
		colly.Async(true),
	)

	// 限制最大并行数量 2
	// 如果 goroutines 时动态创建的,那么限制并发请求还是很有必要的~
	// 还可以通过生成固定数量的 goroutines 来控制并行性。
	c.Limit(&colly.LimitRule{DomainGlob: "*", Parallelism: 2})

	// href 回调
	c.OnHTML("a[href]", func(e *colly.HTMLElement) {
		link := e.Attr("href")
		// Print 
		fmt.Println(link)
		// 在新的现成访问爬到的页面
		e.Request.Visit(link)
	})

	// Start scraping on https://en.wikipedia.org
	c.Visit("https://en.wikipedia.org/")
	// Wait until threads are finished
	c.Wait()
}