Skip to content

快速上手

在与使用Colly之前,确保您拥有最新版本。有关更多详细信息,参阅安装指南

让我们从一些简单的例子开始。 首先,您需要将 Colly 导入到您的项目工程中:

go
import "github.com/gocolly/colly"

1.Collector收集器

Colly 的主要实体是一个 Collector 对象。收集器管理网络通信并负责在收集器作业运行时执行附加的回调。要使用 colly,您必须初始化一个收集器:

go
c := colly.NewCollector()

2.Callbacks回调

您可以将不同类型的回调函数关联到收集器以控制收集作业或检索信息。查看包文档中的相关部分。

(1).添加回调到收集器

go
c.OnRequest(func(r *colly.Request) {
    fmt.Println("Visiting", r.URL)
})

c.OnError(func(_ *colly.Response, err error) {
    log.Println("Something went wrong:", err)
})

c.OnResponse(func(r *colly.Response) {
    fmt.Println("Visited", r.Request.URL)
})

c.OnHTML("a[href]", func(e *colly.HTMLElement) {
    e.Request.Visit(e.Attr("href"))
})

c.OnHTML("tr td:nth-of-type(1)", func(e *colly.HTMLElement) {
    fmt.Println("First column of a table row:", e.Text)
})

c.OnXML("//h1", func(e *colly.XMLElement) {
    fmt.Println(e.Text)
})

c.OnScraped(func(r *colly.Response) {
    fmt.Println("Finished", r.Request.URL)
})

(2).回调的调用顺序

  • OnRequest

    请求前调用

  • OnError

    如果请求期间发生错误,则调用

  • OnResponse

    收到服务器响应后调用

  • OnHTML

    如果接收到的内容是 HTML,则在 OnResponse 之后立即调用

  • OnXML

    如果接收到的内容是 HTML 或 XML,则在 OnHTML 之后立即调用

  • OnScraped

    OnXML 回调后调用