Colly 实战:3 分钟爬取 Shopify 整站 URL
2025-07-14 18:29 更新
官方示例只有 20 行?把它拆成 中文注释 + 扩展模板,让你 3 分钟 不仅拿下 Shopify,还能一键爬任意站点的 sitemap.xml!
一、整体思路(先背下来)
- 目标文件:
/sitemap.xml
(或/sitemap-*.xml
) - XPath 定位:
//urlset/url/loc
取出所有<loc>
标签 - 结果:整站 URL 列表,可用于 SEO 分析 / 全站爬取
二、精简中文代码(15 行)
package main
import (
"fmt"
"os"
"github.com/gocolly/colly/v2"
)
func main() {
if len(os.Args) != 2 {
fmt.Println("用法: go run main.go <域名>")
return
}
domain := os.Args[1] // 例如 shopify.com
var urls []string
// 1. 创建收集器,仅允许目标域名
c := colly.NewCollector(
colly.AllowedDomains(domain, "www."+domain),
)
// 2. 用 XPath 解析 <loc> 标签
c.OnXML("//urlset/url/loc", func(e *colly.XMLElement) {
urls = append(urls, e.Text)
})
// 3. 开始抓取 sitemap.xml
c.Visit("https://www." + domain + "/sitemap.xml")
// 4. 输出统计
fmt.Printf("✅ 共抓取 %d 条 URL\n", len(urls))
for _, u := range urls {
fmt.Println(u)
}
}
三、3 步跑通
步骤 | 命令/操作 | 说明 |
---|---|---|
① 安装依赖 | go mod init sitemap && go get github.com/gocolly/colly/v2 |
一键拉库 |
② 保存文件 | 复制上方代码 → main.go |
零配置 |
③ 一键运行 | go run main.go shopify |
输出 Shopify 全站 URL |
四、结果示例
✅ 共抓取 312 条 URL
https://www.shopify.com/
https://www.shopify.com/blog
https://www.shopify.com/pricing
...
五、1 分钟扩展模板
需求 | 改动 1 行 |
---|---|
爬索引 sitemap | 把 Visit 换成 https://www.xxx.com/sitemap_index.xml |
同时抓多张 sitemap | 用 c.OnXML("//sitemap/loc", ...) 递归 |
保存 CSV | 把 fmt.Println 换成 csv.Writer |
六、常见问题速查
症状 | 原因 | 解决 |
---|---|---|
0 条 URL | 域名无 sitemap | 先访问 /robots.txt 找真实 sitemap 路径 |
403 被拦截 | 缺 User-Agent | 加 colly.UserAgent("...") |
XPath 匹配不到 | 结构变化 | 用浏览器 F12 → Copy → XPath 重新定位 |
七、1 分钟实战:一键爬任意站点
- 打开 终端 → 新建
sitemap.go
- 复制上方代码 → 把
domain
换成你的目标站 - 运行:
go run sitemap.go yourdomain.com
以上内容是否对您有帮助:
更多建议: