0
点赞
收藏
分享

微信扫一扫

Golang:colly 采用 Go 语言编写的 Web 爬虫框架


Golang:colly 采用 Go 语言编写的 Web 爬虫框架_前端

文档:

  • ​​https://go-colly.org/​​
  • ​​https://pkg.go.dev/github.com/gocolly/colly​​
  • ​​https://github.com/gocolly/colly​​

安装

go get github.com/gocolly/colly

示例

package main

import (
"fmt"

"github.com/gocolly/colly"
)

const USER_AGENT = "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/105.0.0.0 Safari/537.36"

func main() {
// 创建 collector
collector := colly.NewCollector()

// 设置UA
collector.UserAgent = USER_AGENT

// 事件监听
collector.OnRequest(func(r *colly.Request) {
fmt.Println("url:", r.URL.String())
// url: https://www.baidu.com/
})

// 解析元素
collector.OnHTML("title", func(e *colly.HTMLElement) {
fmt.Println(e.Text)
// 百度一下,你就知道
})

// 访问网页
collector.Visit("https://www.baidu.com/")
}

事件类型

OnRequest 请求执行之前调用

OnResponse 响应返回之后调用

OnHTML 监听执行 selector

OnXML 监听执行 selector

OnHTMLDetach,取消监听,参数为 selector 字符串

OnXMLDetach,取消监听,参数为 selector 字符串

OnScraped,完成抓取后执行,完成所有工作后执行

OnError,错误回调

请求测试:http://httpbin.org/get



举报

相关推荐

0 条评论