colly 入门指南 ##3

使用colly之前,请确保您拥有最新的版本。有关详细信息,请参阅安装指南。

 

让我们从一些简单的例子开始。

 

首先,你需要导入Colly到你的代码库:

import "github.com/gocolly/colly"

  

收集器

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

c := colly.NewCollector()

  

回调

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

向收集器添加回调

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)
})

  

回调的调用顺序

1. OnRequest

 

在请求之前调用

 

2. OnError

 

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

 

3.OnResponse

 

收到响应后调用

 

4. OnHTML

 

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

 

5. OnXML

 

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

 

6. OnScraped

 

在OnXML回调之后调用

 

原文地址:https://www.cnblogs.com/liujie-php/p/11570781.html