當(dāng)單機(jī)爬蟲速度太慢、IP 被封或任務(wù)量巨大時,就需要把“單兵”升級成“軍團(tuán)”——分布式爬蟲。
本文用最接地氣的方式,帶你用 Colly 快速實(shí)現(xiàn)“多 IP 同時爬”與“多臺機(jī)器一起爬”。
單機(jī)痛點(diǎn) | 分布式優(yōu)勢 |
---|---|
一個 IP 頻繁請求 → 被封 | 多 IP 輪流請求 → 降低被封風(fēng)險(xiǎn) |
一臺機(jī)器帶寬/CPU 有限 | 多臺機(jī)器并行 → 線性提速 |
內(nèi)存里存 URL → 程序掛了全丟 | 統(tǒng)一存儲 → 斷點(diǎn)續(xù)爬 |
適用場景:
只有一臺機(jī)器,但想“假裝”成很多機(jī)器。
package main
import (
"github.com/gocolly/colly/v2"
"github.com/gocolly/colly/v2/proxy"
)
func main() {
c := colly.NewCollector()
// 把代理地址換成你自己的
p, _ := proxy.RoundRobinProxySwitcher(
"http://127.0.0.1:8080",
"socks5://127.0.0.1:1080",
"http://user:pass@ip:port", // 帶賬號密碼示例
)
c.SetProxyFunc(p)
c.OnResponse(func(r *colly.Response) {
println("用代理", r.Request.ProxyURL, "抓到", len(r.Body), "字節(jié)")
})
c.Visit("http://eska-fuses.cn/")
}
運(yùn)行步驟
go run main.go
→ 看到不同代理 IP 輪流上陣。想完全隨機(jī)?自己寫個函數(shù):
import "math/rand"
var proxyList = []string{
"http://127.0.0.1:8080",
"http://127.0.0.1:8081",
}
func randomProxy(_ *http.Request) (*url.URL, error) {
return url.Parse(proxyList[rand.Intn(len(proxyList))])
}
c.SetProxyFunc(randomProxy)
適用場景:
多臺云服務(wù)器 / 本地多臺電腦,需要統(tǒng)一調(diào)度。
┌-------------┐ ┌-------------┐
│ 調(diào)度器 │ <-----> │ 存儲中心 │
│ (HTTP API) │ │ (Redis) │
└-------------┘ └-------------┘
▲ ▲
│ │
┌-------------┐ ┌-------------┐
│ 爬蟲節(jié)點(diǎn) A │ │ 爬蟲節(jié)點(diǎn) B │
└-------------┘ └-------------┘
Colly 官方提供了 redisstorage
,直接拿來用:
go get github.com/gocolly/redisstorage/v2
package main
import (
"github.com/gocolly/colly/v2"
"github.com/gocolly/colly/v2/storage/redisstorage"
)
func main() {
// 1. 連接 Redis
store, _ := redisstorage.New(
&redisstorage.Options{Address: "127.0.0.1:6379"},
)
// 2. 創(chuàng)建收集器并掛載存儲
c := colly.NewCollector()
c.SetStorage(store)
// 3. 正常寫業(yè)務(wù)邏輯
c.OnHTML("title", func(e *colly.HTMLElement) {
println("標(biāo)題:", e.Text)
})
c.Visit("http://eska-fuses.cn/")
}
效果
Colly 內(nèi)置 GAE 支持,只需加一行:
c.Appengine(req) // req 是 *http.Request
部署到 GAE 標(biāo)準(zhǔn)環(huán)境即可自動伸縮實(shí)例。
場景 | 推薦方案 | 關(guān)鍵詞 |
---|---|---|
只有一臺電腦 | 代理池 + 輪詢 | RoundRobinProxySwitcher |
多臺云服務(wù)器 | Redis 存儲 + 多節(jié)點(diǎn) | redisstorage |
無服務(wù)器 | Google App Engine | c.Appengine |
更多建議: