W3Cschool
恭喜您成為首批注冊用戶
獲得88經(jīng)驗值獎勵
官方 30 行示例太簡潔?我把它改成 中文注釋 + 擴(kuò)展模板,讓你 3 分鐘 批量抓取 xkcd 商店的全部商品并保存為 CSV,Excel 直接打開!
https://store.xkcd.com/collections/everything
.product-grid-item
→ 名稱 / 價格 / 鏈接 / 圖片 .next a[href]
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. 創(chuàng)建收集器
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)
}
步驟 | 命令/操作 | 說明 |
---|---|---|
① 安裝 | go mod init xkcd && go get github.com/gocolly/colly/v2 |
一鍵拉庫 |
② 保存 | 復(fù)制上方代碼 → main.go |
零配置 |
③ 運(yùn)行 | go run main.go |
生成 xkcd_store.csv |
商品名 | 價格 | 商品鏈接 | 圖片鏈接 |
---|---|---|---|
xkcd Volume 0 | $15.00 | https://store.xkcd.com/products/volume-0 | https://cdn.shopify.com/...jpg |
xkcd Volume 1 | $15.00 | ... | ... |
需求 | 改動 2 處 |
---|---|
換域名 | 把 AllowedDomains 和 Visit 換成目標(biāo)商店 |
換選擇器 | F12 找到商品卡片對應(yīng)的 CSS 類 |
癥狀 | 原因 | 解決 |
---|---|---|
0 條數(shù)據(jù) | 頁面改版 | 更新 .product-grid-item 等選擇器 |
403 被攔截 | 缺 UA | 加 UserAgent("Mozilla/5.0...") |
圖片不顯示 | 缺協(xié)議 | 加 https: 前綴 |
Copyright©2021 w3cschool編程獅|閩ICP備15016281號-3|閩公網(wǎng)安備35020302033924號
違法和不良信息舉報電話:173-0602-2364|舉報郵箱:jubao@eeedong.com
掃描二維碼
下載編程獅App
編程獅公眾號
聯(lián)系方式:
更多建議: