Colly 实战:3 分钟爬完 xkcd 周边商店

2025-07-14 18:34 更新

官方 30 行示例太简洁?我把它改成 中文注释 + 扩展模板,让你 3 分钟 批量抓取 xkcd 商店的全部商品并保存为 CSV,Excel 直接打开!

一、整体思路(先背下来)

  1. 入口https://store.xkcd.com/collections/everything
  2. 解析商品.product-grid-item → 名称 / 价格 / 链接 / 图片
  3. 自动翻页.next a[href]
  4. 结果:CSV 文件,含表头

二、精简中文代码(20 行)

package main


import (
    "encoding/csv"
    "log"
    "os"


    "github.com/gocolly/colly/v2"
)


func main() {
    fileName := "xkcd_store.csv"
    file, _ := os.Create(fileName)
    defer file.Close()


    writer := csv.NewWriter(file)
    defer writer.Flush()


    // 1. 写入表头
    writer.Write([]string{"商品名", "价格", "商品链接", "图片链接"})


    // 2. 创建收集器
    c := colly.NewCollector(colly.AllowedDomains("store.xkcd.com"))


    // 3. 解析单个商品
    c.OnHTML(".product-grid-item", func(e *colly.HTMLElement) {
        writer.Write([]string{
            e.ChildAttr("a", "title"),
            e.ChildText("span"),
            e.Request.AbsoluteURL(e.ChildAttr("a", "href")),
            "https:" + e.ChildAttr("img", "src"),
        })
    })


    // 4. 自动翻页
    c.OnHTML(`.next a[href]`, func(e *colly.HTMLElement) {
        e.Request.Visit(e.Attr("href"))
    })


    // 5. 启动
    c.Visit("https://store.xkcd.com/collections/everything")
    log.Printf("✅ 爬取完成,查看 %s\n", fileName)
}

三、3 步跑通

步骤 命令/操作 说明
① 安装 go mod init xkcd && go get github.com/gocolly/colly/v2 一键拉库
② 保存 复制上方代码 → main.go 零配置
③ 运行 go run main.go 生成 xkcd_store.csv

四、结果示例(CSV)

商品名 价格 商品链接 图片链接
xkcd Volume 0 $15.00 https://store.xkcd.com/products/volume-0 https://cdn.shopify.com/...jpg
xkcd Volume 1 $15.00 ... ...

五、1 分钟扩展:爬任意 Shopify 商店

需求 改动 2 处
换域名 把 AllowedDomains 和 Visit 换成目标商店
换选择器 F12 找到商品卡片对应的 CSS 类

六、常见问题速查

症状 原因 解决
0 条数据 页面改版 更新 .product-grid-item 等选择器
403 被拦截 缺 UA 加 UserAgent("Mozilla/5.0...")
图片不显示 缺协议 加 https: 前缀
以上内容是否对您有帮助:
在线笔记
App下载
App下载

扫描二维码

下载编程狮App

公众号
微信公众号

编程狮公众号