Colly 爬虫即服务:一行命令把爬虫变 HTTP API
2025-07-14 16:59 更新
不想写脚本、不想跑命令?把爬虫封装成 HTTP API,浏览器或 Postman 直接调:
http://localhost:7171/?url=https://www.w3cschool.cn
→ 立即返回页面信息!
一、示例:
爬编程狮并返回 JSON,复制即可跑:
package main
import (
"encoding/json"
"log"
"net/http"
"github.com/gocolly/colly/v2"
)
// 返回结构体:状态码 + 链接统计
type PageInfo struct {
StatusCode int `json:"status_code"`
Title string `json:"title"`
Links map[string]string `json:"links"` // 文本→URL
}
func handler(w http.ResponseWriter, r *http.Request) {
url := r.URL.Query().Get("url")
if url == "" {
http.Error(w, "缺少 url 参数", http.StatusBadRequest)
return
}
c := colly.NewCollector(
colly.AllowedDomains("w3cschool.cn", "www.w3cschool.cn"),
)
info := &PageInfo{
Links: make(map[string]string),
}
// 1. 提取标题
c.OnHTML("title", func(e *colly.HTMLElement) {
info.Title = e.Text
})
// 2. 统计所有超链接
c.OnHTML("a[href]", func(e *colly.HTMLElement) {
link := e.Request.AbsoluteURL(e.Attr("href"))
if link != "" {
info.Links[e.Text] = link
}
})
// 3. 记录状态码
c.OnResponse(func(r *colly.Response) {
info.StatusCode = r.StatusCode
})
c.OnError(func(r *colly.Response, err error) {
info.StatusCode = r.StatusCode
})
// 4. 开始爬取
_ = c.Visit(url)
// 5. 返回 JSON
w.Header().Set("Content-Type", "application/json")
_ = json.NewEncoder(w).Encode(info)
}
func main() {
addr := ":7171"
http.HandleFunc("/", handler)
log.Println("🚀 爬虫服务已启动:http://localhost" + addr + "/?url=目标网址")
log.Fatal(http.ListenAndServe(addr, nil))
}
二、3 步直接体验
步骤 | 命令/操作 | 说明 |
---|---|---|
① 保存代码 | 复制上方内容 → 保存为 server.go |
依赖已是最新版 |
② 运行服务 | go run server.go |
终端出现 “🚀 爬虫服务已启动” |
③ 浏览器访问 | http://localhost:7171/?url=https://www.w3cschool.cn/go |
返回 JSON 标题+链接 |
三、返回示例(浏览器/Postman)
{
"status_code": 200,
"title": "Go 语言教程 | 编程狮",
"links": {
"Python 教程": "https://www.w3cschool.cn/python",
"Java 教程": "https://www.w3cschool.cn/java"
}
}
四、3 分钟进阶玩法
需求 | 做法 |
---|---|
分布式部署 | 用云 Redis 存储 → 多台实例共享进度(见 Redis 持久化教程) |
并发限速 | 在 handler 里加 c.Limit(&colly.LimitRule{...}) |
登录态共享 | 爬需要登录的页面 → 把 Cookie 提前写入 Redis |
五、1 分钟动手实验
- 打开 终端 → 新建
server.go
。 - 复制代码 →
go run server.go
。 - 浏览器访问:
http://localhost:7171/?url=https://www.w3cschool.cn
立即看到 JSON 结果!
以上内容是否对您有帮助:
更多建议: