Colly 實(shí)戰(zhàn):3 分鐘爬完 Reddit 熱帖

2025-07-14 18:24 更新

官方示例 40 行不夠直觀?我把它壓縮成 20 行中文注釋版,支持 任意子版塊、自動(dòng)翻頁(yè)、限速防封,直接輸出 JSON!

一、整體思路(先背下來)

  1. 入口r/programming/hot
  2. 解析每條帖子:標(biāo)題、鏈接、評(píng)論數(shù)
  3. 自動(dòng)下一頁(yè).next-button
  4. 限速:并發(fā) 2 + 隨機(jī) 5 秒延遲

二、精簡(jiǎn)中文代碼(20 行)

package main


import (
    "encoding/json"
    "flag"
    "fmt"
    "time"


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


// 帖子結(jié)構(gòu)體
type Post struct {
    Title    string    `json:"標(biāo)題"`
    Link     string    `json:"鏈接"`
    Comments string    `json:"評(píng)論鏈接"`
    Crawled  time.Time `json:"抓取時(shí)間"`
}


func main() {
    // 1. 命令行參數(shù):-sub=programming
    sub := flag.String("sub", "programming", "子版塊名稱")
    flag.Parse()


    var posts []Post
    c := colly.NewCollector(
        colly.AllowedDomains("www.reddit.com"),
        colly.Async(true),
    )


    // 2. 解析帖子
    c.OnHTML(".top-matter", func(e *colly.HTMLElement) {
        posts = append(posts, Post{
            Title:    e.ChildText("a[data-event-action=title]"),
            Link:     e.ChildAttr("a[data-event-action=title]", "href"),
            Comments: e.ChildAttr("a[data-event-action=comments]", "href"),
            Crawled:  time.Now(),
        })
    })


    // 3. 自動(dòng)翻頁(yè)
    c.OnHTML("span.next-button", func(e *colly.HTMLElement) {
        e.Request.Visit(e.ChildAttr("a", "href"))
    })


    // 4. 限速防封
    c.Limit(&colly.LimitRule{
        Parallelism: 2,
        RandomDelay: 5 * time.Second,
    })


    // 5. 啟動(dòng)
    startURL := fmt.Sprintf("https://www.reddit.com/r/%s/hot/", *sub)
    c.Visit(startURL)
    c.Wait()


    // 6. 輸出 JSON
    data, _ := json.MarshalIndent(posts, "", "  ")
    fmt.Println(string(data))
}

三、3 步跑通

步驟 命令/操作 說明
① 安裝 go mod init reddit && go get github.com/gocolly/colly/v2 一鍵拉庫(kù)
② 保存 復(fù)制上方代碼 → main.go 零配置
③ 運(yùn)行 go run main.go -sub=programming > posts.json 生成 JSON

四、結(jié)果示例(posts.json)

[
  {
    "標(biāo)題": "Show HN: A tiny tool written in Go to ...",
    "鏈接": "https://github.com/...",
    "評(píng)論鏈接": "https://www.reddit.com/r/programming/comments/...",
    "抓取時(shí)間": "2024-07-14T12:34:56Z"
  }
  // ...更多帖子
]

五、常見問題速查

癥狀 原因 解決
0 條數(shù)據(jù) 反爬 / 改版 加 User-Agent 或更新選擇器
403 錯(cuò)誤 限速 調(diào)大 RandomDelay 或降 Parallelism
下一頁(yè)失效 新版 Reddit 把選擇器換成 a[rel="nofollow next"]

六、1 分鐘擴(kuò)展

需求 改動(dòng) 1 行
爬多個(gè)版塊 go run main.go -sub=golang,python
存 CSV 把 JSON 編碼換成 csv.Writer
存數(shù)據(jù)庫(kù) 在 OnHTML 里寫 INSERT
以上內(nèi)容是否對(duì)您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號(hào)
微信公眾號(hào)

編程獅公眾號(hào)