Skip to content

Url过滤器


go
package main

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

func main() {
	// 初始化 collector
	c := colly.NewCollector(
		// 访问httpbin.org 网站的根url 并且 urls 以 "e" or "h" 开始的
		colly.URLFilters(
			regexp.MustCompile("http://httpbin\\.org/(|e.+)$"),
			regexp.MustCompile("http://httpbin\\.org/h.+"),
		),
	)

	// href 回调
	c.OnHTML("a[href]", func(e *colly.HTMLElement) {
		link := e.Attr("href")
		// Print link
		fmt.Printf("Link found: %q -> %s\n", e.Text, link)
		// 仅访问与任何 URLFilter 正则表达式匹配的链接
		c.Visit(e.Request.AbsoluteURL(link))
	})

	// 请求之前 打印"Visiting ..."
	c.OnRequest(func(r *colly.Request) {
		fmt.Println("Visiting", r.URL.String())
	})

	//开始爬取  http://httpbin.org
	c.Visit("http://httpbin.org/")
}