问题描述
初学go,制作可以爬取百度热搜的爬虫,但是最终得到两个切片,不知道怎么弄成json,搜索发现网上资源太少了。
用了goquery和gin两个库。
理想效果是访问http://【ip】/api/v1/baidu/hot返回:
[
{
"title": "...",
"img": "https://..."
},
{
"title": "...",
"img": "https://..."
}
// .......
]
相关代码
package main
import (
"net/http"
"strings"
"github.com/PuerkitoBio/goquery"
"github.com/gin-gonic/gin"
)
func main() {
r := gin.Default()
// api
api := r.Group("/api/v1")
{
baidu := api.Group("/baidu")
{
baidu.GET("/hot", getBaiduHotList)
}
api.GET("/", apiTest)
}
// 端口
r.Run(":80")
}
func apiTest(c *gin.Context) {
c.JSON(200, gin.H{
"msg": "200",
})
}
var (
img []string
title []string
)
func getBaiduHotList(c *gin.Context) {
resp, err := http.Get("https://top.baidu.com/board")
if err != nil {
panic(err)
}
dom, err := goquery.NewDocumentFromReader(resp.Body)
if err != nil {
panic(err)
}
dom.Find(".theme-hot .active-item_1Em2h .c-single-text-ellipsis").Each(
func(i int, s *goquery.Selection) {
title := append(title, strings.Join(strings.Fields(s.Text()), ""))
// 然后就不知道怎么搞了
})
dom.Find(".theme-hot .active-item-img_3i_Tx").Each(
func(i int, s *goquery.Selection) {
src, _ := s.Attr("src")
img := append(img, strings.Join(strings.Fields(src), ""))
// 然后就不知道怎么搞了
})
}
望大佬们指导一下,非常感谢。
只是抓包的话,不需要用gin库,转json的话需要用json库
调用方法
抓取结果
注意转Json时结构体中变量首字母大写才可以导出