W3Cschool
恭喜您成為首批注冊(cè)用戶
獲得88經(jīng)驗(yàn)值獎(jiǎng)勵(lì)
官方示例 40 行不夠直觀?我把它壓縮成 20 行中文注釋版,支持 任意子版塊、自動(dòng)翻頁(yè)、限速防封,直接輸出 JSON!
r/programming/hot
.next-button
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))
}
步驟 | 命令/操作 | 說明 |
---|---|---|
① 安裝 | 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 |
[
{
"標(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"] |
需求 | 改動(dòng) 1 行 |
---|---|
爬多個(gè)版塊 | go run main.go -sub=golang,python |
存 CSV | 把 JSON 編碼換成 csv.Writer |
存數(shù)據(jù)庫(kù) | 在 OnHTML 里寫 INSERT |
Copyright©2021 w3cschool編程獅|閩ICP備15016281號(hào)-3|閩公網(wǎng)安備35020302033924號(hào)
違法和不良信息舉報(bào)電話:173-0602-2364|舉報(bào)郵箱:jubao@eeedong.com
掃描二維碼
下載編程獅App
編程獅公眾號(hào)
聯(lián)系方式:
更多建議: