Colly 基础示例:5 分钟写出你的第一个爬虫
2025-07-11 15:36 更新
零依赖、零配置,复制即可运行!
一、完整代码(中文注释)
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 步运行
- 安装 Colly
go mod init w3c-demo go get github.com/gocolly/colly/v2
- 保存文件
把上面代码保存为main.go
。
- 一键运行
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
→ 粘贴代码 → 运行,立刻看到自家首页链接滚滚而来!
以上内容是否对您有帮助:
更多建议: