codecamp

Colly 基础示例:5 分钟写出你的第一个爬虫

零依赖、零配置,复制即可运行!

一、完整代码(中文注释)

package main


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


func main() {
    // 1. 创建收集器,只允许访问编程狮域名
    c := colly.NewCollector(
        colly.AllowedDomains("www.w3cschool.cn", "w3cschool.cn"),
    )


    // 2. 发现 <a href="..."> 标签就打印并继续访问
    c.OnHTML("a[href]", func(e *colly.HTMLElement) {
        link := e.Attr("href")
        fmt.Printf("发现链接:%s → %s\n", e.Text, link)


        // 自动补全绝对路径后再访问
        absoluteURL := e.Request.AbsoluteURL(link)
        c.Visit(absoluteURL)
    })


    // 3. 每次请求前打印日志
    c.OnRequest(func(r *colly.Request) {
        fmt.Println("正在访问:", r.URL.String())
    })


    // 4. 从编程狮首页开始
    c.Visit("https://www.w3cschool.cn/")
}

二、3 步运行

  1. 安装 Colly
    go mod init w3c-demo
    go get github.com/gocolly/colly/v2

  1. 保存文件
    把上面代码保存为 main.go

  1. 一键运行
    go run main.go

    终端会不断输出:

    正在访问: https://www.w3cschool.cn/
    发现链接:Go 教程 → /go
    正在访问: https://www.w3cschool.cn/go
    ...

三、小白问答

疑问 一句话解答
为什么只爬这两个域名? AllowedDomains 防止爬到外站。
如何只爬 2 层? 加 c.MaxDepth = 2
如何停止无限爬? Ctrl+C 或加 MaxDepth

四、1 分钟实验

打开 Go 环境 → 新建 main.go → 粘贴代码 → 运行,立刻看到自家首页链接滚滚而来!

Colly 扩展插件:给爬虫装上“瑞士军刀”
Colly 错误处理:让爬虫永不“崩溃”
温馨提示
下载编程狮App,免费阅读超1000+编程语言教程
取消
确定
目录

关闭

MIP.setData({ 'pageTheme' : getCookie('pageTheme') || {'day':true, 'night':false}, 'pageFontSize' : getCookie('pageFontSize') || 20 }); MIP.watch('pageTheme', function(newValue){ setCookie('pageTheme', JSON.stringify(newValue)) }); MIP.watch('pageFontSize', function(newValue){ setCookie('pageFontSize', newValue) }); function setCookie(name, value){ var days = 1; var exp = new Date(); exp.setTime(exp.getTime() + days*24*60*60*1000); document.cookie = name + '=' + value + ';expires=' + exp.toUTCString(); } function getCookie(name){ var reg = new RegExp('(^| )' + name + '=([^;]*)(;|$)'); return document.cookie.match(reg) ? JSON.parse(document.cookie.match(reg)[2]) : null; }