Go 實戰 -三-: 基金分析系統 - 爬取收益榜單
- 流程介紹
- 頁面分析
- 爬蟲腳本
3.1 編寫結構體
代碼文件位置:service/crawl/fund/top_crawl.go
// 對應每一行的基金信息
type fundItem struct {
FundCode string `selector:"td:nth-of-type(1)"`
FundName string `selector:"td:nth-of-type(2)"`
NetWorth string `selector:"td:nth-of-type(3) > span.fb"`
TopDate string `selector:"td:nth-of-type(3) > span.date"`
DayChange string `selector:"td:nth-of-type(4)"`
WeekChange string `selector:"td:nth-of-type(5)"`
MouthChange string `selector:"td:nth-of-type(6)"`
ThreeMouthChange string `selector:"td:nth-of-type(7)"`
SixMouthChange string `selector:"td:nth-of-type(8)"`
YearChange string `selector:"td:nth-of-type(9)"`
TwoYearChange string `selector:"td:nth-of-type(10)"`
ThreeYearChange string `selector:"td:nth-of-type(11)"`
CurrentChange string `selector:"td:nth-of-type(12)"`
CreateChange string `selector:"td:nth-of-type(13)"`
}
type TopCrawlService struct {
Item []*fundItem `selector:"tr"`
}
td:nth-of-type(n)
代表每行的第n
列,@注意:這裏的 NetWorth 和 TopDate, 取的都是第 3 列的數據
3.2 爬取網頁
代碼文件位置:service/crawl/fund/top_crawl.go
// CrawlHtml 抓取網頁信息
func (f *TopCrawlService) CrawlHtml() {
collector := colly.NewCollector(
colly.UserAgent(crawl.UserAgent),
)
// 設置Header
collector.OnRequest(func(request *colly.Request) {
request.Headers.Set("Accept-Language", "zh-CN,zh;q=0.9,en;q=0.8,zh-TW;q=0.7")
})
collector.OnError(func(response *colly.Response, err error) {
global.GvaLogger.Sugar().Errorf("基金排行榜,信息獲取失敗: %s", err)
return
})
// 選中id=tblite_hh的table,使用Unmarshal方法會把每行數據,自動映射結構體
collector.OnHTML("#tblite_hh", func(element *colly.HTMLElement) {
err := element.Unmarshal(f)
if err != nil {
fmt.Println("element.Unmarshal error: ", err)
}
})
// 獲取響應
collector.OnResponse(func(response *colly.Response) {
// 將返回中的html中所有的%去掉
newBody := strings.ReplaceAll(string(response.Body), "%", "")
response.Body = []byte(newBody)
})
// 爬取收益排行榜,(默認是按照近一年的排行)
err := collector.Visit("https://fundact.eastmoney.com/banner/hh.html")
if err != nil {
global.GvaLogger.Sugar().Errorf("基金排行榜爬取失敗: %s", err)
}
}
3.3 數據清洗
代碼文件位置:service/crawl/fund/top_crawl.go
// ConvertEntity 格式化類型
func (f *TopCrawlService) ConvertEntity() []entity.FundDayTop {
var topList []entity.FundDayTop
for _, item := range f.Item {
if item.FundCode == "" {
continue
}
fundTmp := entity.FundDayTop{}
fundTmp.FundCode = item.FundCode
// 格式化日期
format := time.Now().Format("2006")
fundTmp.TopDate = fmt.Sprintf("%s-%s", format, item.TopDate)
// 轉換編碼
fundTmp.FundName, _ = utils.GbkToUtf8(item.FundName)
// 字符串轉浮點型
fundTmp.NetWorth, _ = strconv.ParseFloat(item.NetWorth, 64)
fundTmp.DayChange, _ = strconv.ParseFloat(item.DayChange, 64)
fundTmp.WeekChange, _ = strconv.ParseFloat(item.WeekChange, 64)
fundTmp.MouthChange, _ = strconv.ParseFloat(item.MouthChange, 64)
fundTmp.ThreeMouthChange, _ = strconv.ParseFloat(item.ThreeMouthChange, 64)
fundTmp.SixMouthChange, _ = strconv.ParseFloat(item.SixMouthChange, 64)
fundTmp.YearChange, _ = strconv.ParseFloat(item.YearChange, 64)
fundTmp.TwoYearChange, _ = strconv.ParseFloat(item.TwoYearChange, 64)
fundTmp.ThreeYearChange, _ = strconv.ParseFloat(item.ThreeYearChange, 64)
fundTmp.CurrentChange, _ = strconv.ParseFloat(item.CurrentChange, 64)
fundTmp.CreateChange, _ = strconv.ParseFloat(item.CreateChange, 64)
topList = append(topList, fundTmp)
}
return topList
}
- 定時任務
4.1 實現cron.Job
接口
代碼文件位置:crontab/fund_top_cron.go
type FundTopCron struct {}
func (c FundTopCron) Run() {
fmt.Println("基金排行榜-定時任務準備運行....")
f := &fund.TopCrawlService{}
// 爬取網頁
f.CrawlHtml()
// 轉換數據
fundDayTopList := f.ConvertEntity()
// 入庫
if !f.ExistTopDate() {
result := global.GvaMysqlClient.Create(fundDayTopList)
if result.Error != nil {
global.GvaLogger.Sugar().Errorf("本次任務保存數據失敗:%條",result.Error)
return
}
global.GvaLogger.Sugar().Infof("本次任務保存數據:%條",result.RowsAffected)
return
}
global.GvaLogger.Sugar().Info("任務運行成功,無數據要保存!")
fmt.Println("基金排行榜-定時任務運行結束!")
}
4.2 註冊任務
代碼文件位置:initialize/cron.go
// 添加Job任務
func addJob(c *cron.Cron) {
...
// 爬取每日基金排行榜單:每天16:30執行
// _, _ = c.AddJob("0 30 16 */1 * *", crontab.FundTopCron{})
// 爲了測試,先寫成 每10s一次
_, _ = c.AddJob("@every 10s", crontab.FundTopCron{})
}
- 效果展示
5.1 運行項目
...
[GIN-debug] GET /demo/es/create --> 52lu/fund-analye-system/api/demo.CreateIndex (3 handlers)
[GIN-debug] GET /demo/es/searchById --> 52lu/fund-analye-system/api/demo.SearchById (3 handlers)
【 當前環境: dev 當前版本: v1.0.0 接口地址: http://0.0.0.0:8088 】
基金排行榜-定時任務準備運行....
基金排行榜-定時任務運行結束!
5.2 數據表
本文由 Readfog 進行 AMP 轉碼,版權歸原作者所有。
來源:https://mp.weixin.qq.com/s/SX_AyKAjpkEHAKBxLaCZdA