您当前的位置: 首页 >  golang

彭世瑜

暂无认证

  • 3浏览

    0关注

    2791博文

    0收益

  • 0浏览

    0点赞

    0打赏

    0留言

私信
关注
热门博文

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

彭世瑜 发布时间:2022-09-06 10:47:00 ,浏览量:3

在这里插入图片描述

文档:

  • 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

参考 重磅推荐:这可能是最知名的 Go 爬虫框架

关注
打赏
1665367115
查看更多评论
立即登录/注册

微信扫码登录

0.0597s