Skip to content

请求上下文


go
package main

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

func main() {
	// 初始化 collector
	c := colly.NewCollector()

	// 请求之前,将URL 和key ‘url’ 放入请求的 context中
	c.OnRequest(func(r *colly.Request) {
		r.Ctx.Put("url", r.URL.String())
	})

	// 请求之后从请求的上下文中取出 url
	c.OnResponse(func(r *colly.Response) {
		fmt.Println(r.Ctx.Get("url"))
	})

	// 开始爬取 https://en.wikipedia.org
	c.Visit("https://en.wikipedia.org/")
}