W3Cschool
恭喜您成為首批注冊用戶
獲得88經(jīng)驗(yàn)值獎勵
不想寫腳本、不想跑命令?把爬蟲封裝成 HTTP API,瀏覽器或 Postman 直接調(diào):
http://localhost:7171/?url=http://m.o2fo.com
→ 立即返回頁面信息!
爬編程獅并返回 JSON,復(fù)制即可跑:
package main
import (
"encoding/json"
"log"
"net/http"
"github.com/gocolly/colly/v2"
)
// 返回結(jié)構(gòu)體:狀態(tài)碼 + 鏈接統(tǒng)計
type PageInfo struct {
StatusCode int `json:"status_code"`
Title string `json:"title"`
Links map[string]string `json:"links"` // 文本→URL
}
func handler(w http.ResponseWriter, r *http.Request) {
url := r.URL.Query().Get("url")
if url == "" {
http.Error(w, "缺少 url 參數(shù)", http.StatusBadRequest)
return
}
c := colly.NewCollector(
colly.AllowedDomains("w3cschool.cn", "m.o2fo.com"),
)
info := &PageInfo{
Links: make(map[string]string),
}
// 1. 提取標(biāo)題
c.OnHTML("title", func(e *colly.HTMLElement) {
info.Title = e.Text
})
// 2. 統(tǒng)計所有超鏈接
c.OnHTML("a[href]", func(e *colly.HTMLElement) {
link := e.Request.AbsoluteURL(e.Attr("href"))
if link != "" {
info.Links[e.Text] = link
}
})
// 3. 記錄狀態(tài)碼
c.OnResponse(func(r *colly.Response) {
info.StatusCode = r.StatusCode
})
c.OnError(func(r *colly.Response, err error) {
info.StatusCode = r.StatusCode
})
// 4. 開始爬取
_ = c.Visit(url)
// 5. 返回 JSON
w.Header().Set("Content-Type", "application/json")
_ = json.NewEncoder(w).Encode(info)
}
func main() {
addr := ":7171"
http.HandleFunc("/", handler)
log.Println("?? 爬蟲服務(wù)已啟動:http://localhost" + addr + "/?url=目標(biāo)網(wǎng)址")
log.Fatal(http.ListenAndServe(addr, nil))
}
步驟 | 命令/操作 | 說明 |
---|---|---|
① 保存代碼 | 復(fù)制上方內(nèi)容 → 保存為 server.go |
依賴已是最新版 |
② 運(yùn)行服務(wù) | go run server.go |
終端出現(xiàn) “?? 爬蟲服務(wù)已啟動” |
③ 瀏覽器訪問 | http://localhost:7171/?url=http://m.o2fo.com/go |
返回 JSON 標(biāo)題+鏈接 |
{
"status_code": 200,
"title": "Go 語言教程 | 編程獅",
"links": {
"Python 教程": "http://m.o2fo.com/python",
"Java 教程": "http://m.o2fo.com/java"
}
}
需求 | 做法 |
---|---|
分布式部署 | 用云 Redis 存儲 → 多臺實(shí)例共享進(jìn)度(見 Redis 持久化教程) |
并發(fā)限速 | 在 handler 里加 c.Limit(&colly.LimitRule{...}) |
登錄態(tài)共享 | 爬需要登錄的頁面 → 把 Cookie 提前寫入 Redis |
server.go
。 go run server.go
。 http://localhost:7171/?url=http://m.o2fo.com
Copyright©2021 w3cschool編程獅|閩ICP備15016281號-3|閩公網(wǎng)安備35020302033924號
違法和不良信息舉報電話:173-0602-2364|舉報郵箱:jubao@eeedong.com
掃描二維碼
下載編程獅App
編程獅公眾號
聯(lián)系方式:
更多建議: