定义结构体[1]

表示某个货币信息


type CoinInfo struct {
	Rank string `json:"rank"`
	Name string `json:"name"`
	CurrentCount string `json:"current_count"`
	CurrentPrice string `json:"current_price"`
	CurrentMark string `json:"current_mark"`
	Count string `json:"count"`
	Change string `json:"change"`

}

抓取和解析信息

返回所有的货币信息,是一个货币信息数组


func queryCoinInfo() []CoinInfo {
	doc, err := goquery.NewDocument("https://www.feixiaohao.com/")

	if err != nil {
		fmt.Print(err.Error())
		return nil
	}

	var coinInfos [] CoinInfo
	//解析document
	doc.Find("#table tbody tr").Each(func(i int, selection *goquery.Selection) {
		var coinInfo CoinInfo
		Rank := selection.Find("td").Eq(0).Text()
		CoinName := strings.TrimSpace(selection.Find("td").Eq(1).Text())
		CurrentCount := selection.Find("td").Eq(2).Text()
		CurrentPrice := selection.Find("td").Eq(3).Text()
		CurrentMark := selection.Find("td").Eq(4).Text()
		Count := selection.Find("td").Eq(5).Text()
		Change := strings.TrimSpace(selection.Find("td").Eq(6).Text())
		//生成一个对象
		coinInfo = CoinInfo{
			Rank:Rank,
			Name:CoinName,
			CurrentCount:CurrentCount,
			CurrentPrice:CurrentPrice,
			CurrentMark:CurrentMark,
			Count:Count,
			Change:Change,
		}
		//添加每一个对象到数组中
		coinInfos = append(coinInfos, coinInfo)

	})

	return coinInfos
}

接口生成

使用gin监听一个路由,然后生成接口


func main() {

	data := queryCoinInfo()

	r := gin.Default()
	//使用gin router监听get
	r.GET("/", func(context *gin.Context) {
		context.JSON(200, &data)
	})

	r.Run(":8080")
}

依赖

别忘了安装依赖哦


go get github.com/PuerkitoBio/goquery
go get github.com/gin-gonic/gin

最后

大概的结果是这样的

[
  {
    "rank": "1",
    "name": "BTC-比特币",
    "current_count": "¥8,113亿",
    "current_price": "¥46,833",
    "current_mark": "1,732万",
    "count": "¥3,729,231万",
    "change": "6.48%"
  },
  {
    "rank": "2",
    "name": "ETH-以太坊",
    "current_count": "¥1,535亿",
    "current_price": "¥1,496",
    "current_mark": "10,258万",
    "count": "¥1,581,542万",
    "change": "6.72%"
  }
  //...
]

上文就是一个简易的爬虫示例,主要使用的是goquery和gin,你学会了吗。


  1. 题图 ↩︎