golang访问Google Trends数据的非官方API插件库gogtrends的使用

Golang访问Google Trends数据的非官方API插件库gogtrends的使用

介绍

gogtrends是一个允许从Google Trends获取报告的API封装库。它是一个非官方的Google Trends API for Golang实现。

安装

使用以下命令安装gogtrends:

go get -u github.com/groovili/gogtrends

调试

要查看请求-响应详情,可以使用:

gogtrends.Debug(true)

使用方法

基本参数说明

  • hl - 字符串,用户界面语言
  • loc - 字符串,大写的地区(geo)国家代码,例如"US"表示美国
  • cat - 字符串,实时趋势的小写类别,例如"all"表示所有类别
  • exploreReq - ExploreRequest结构体,表示搜索或比较项
  • widget - ExploreWidget结构体,每个方法特有的,可以通过Explore方法获取

可用方法

  1. Daily(ctx context.Context, hl, loc string) ([]*TrendingSearch, error) - 按天排序的每日趋势及其相关文章
  2. Realtime(ctx context.Context, hl, loc, cat string) ([]*TrendingStory, error) - 包含文章和来源的实时趋势
  3. Search(ctx context.Context, word, hl string) ([]*KeywordTopic, error) - 与搜索相关的词/主题(最多5个结果)
  4. Explore(ctx context.Context, r *ExploreRequest, hl string) ([]*ExploreWidget, error) - 包含token的小部件
  5. InterestOverTime(ctx context.Context, w *ExploreWidget, hl string) ([]*Timeline, error) - 随时间变化的兴趣点
  6. InterestByLocation(ctx context.Context, w *ExploreWidget, hl string) ([]*GeoMap, error) - 按位置划分的兴趣
  7. Related(ctx context.Context, w *ExploreWidget, hl string) ([]*RankedKeyword, error) - 相关主题或查询
  8. TrendsCategories() map[string]string - 实时趋势的可用类别
  9. ExploreCategories(ctx context.Context) (*ExploreCatTree, error) - 用于探索和比较的类别树
  10. ExploreLocations(ctx context.Context) (*ExploreLocTree, error) - 用于探索和比较的位置树

示例代码

获取每日趋势

// Daily trends
ctx := context.Background()
dailySearches, err := gogtrends.Daily(ctx, "EN", "US")

获取实时趋势

// Get available trends categories and realtime trends
cats := gogtrends.TrendsCategories()
realtime, err := gogtrends.Realtime(ctx, "EN", "US", "all")

探索关键词并获取统计信息

// Explore available widgets for keywords and get all available stats for it
explore, err := gogtrends.Explore(ctx, 
    &gogtrends.ExploreRequest{
        ComparisonItems: []*gogtrends.ComparisonItem{
            {
                Keyword: "Go",
                Geo:     "US",
                Time:    "today 12-m",
            },
        },
        Category: 31, // Programming category
        Property: "",
    }, "EN")

// Interest over time
overTime, err := gogtrends.InterestOverTime(ctx, explore[0], "EN")

// Interest by location
byLoc, err := gogtrends.InterestByLocation(ctx, explore[1], "EN")

// Related topics for keyword
relT, err := gogtrends.Related(ctx, explore[2], "EN")

// Related queries for keyword
relQ, err := gogtrends.Related(ctx, explore[3], "EN")

比较关键词兴趣

// Compare keywords interest
compare, err := gogtrends.Explore(ctx, 
    &gogtrends.ExploreRequest{
        ComparisonItems: []*gogtrends.ComparisonItem{
            {
                Keyword: "Go",
                Geo:     "US",
                Time:    "today 12-m",
            },
            {
                Keyword: "Python",
                Geo:     "US",
                Time:    "today 12-m",
            },
            {
                Keyword: "PHP",
                Geo:     "US",
                Time:    "today 12-m",
            },                               
        },
        Category: 31, // Programming category
        Property: "",
    }, "EN")

许可证

该软件包根据MIT许可证分发。


更多关于golang访问Google Trends数据的非官方API插件库gogtrends的使用的实战教程也可以访问 https://www.itying.com/category-94-b0.html

1 回复

更多关于golang访问Google Trends数据的非官方API插件库gogtrends的使用的实战系列教程也可以访问 https://www.itying.com/category-94-b0.html


使用gogtrends访问Google Trends数据

gogtrends是一个非官方的Go语言库,用于访问Google Trends数据。它提供了简单易用的API来获取热门搜索、相关查询、按地区趋势等数据。

安装

go get github.com/groovili/gogtrends

基本使用示例

1. 获取每日热门搜索

package main

import (
	"fmt"
	"log"
	"time"

	"github.com/groovili/gogtrends"
)

func main() {
	// 创建客户端
	client := gogtrends.NewClient()

	// 获取每日热门搜索
	trends, err := client.Daily(time.Now(), "US", "en-US")
	if err != nil {
		log.Fatal(err)
	}

	// 打印结果
	for _, trend := range trends {
		fmt.Printf("标题: %s\n", trend.Title)
		fmt.Printf("搜索量: %d\n", trend.Traffic)
		fmt.Printf("链接: %s\n", trend.Link)
		fmt.Println("------------------------")
	}
}

2. 获取实时趋势

func getRealtimeTrends() {
	client := gogtrends.NewClient()
	
	// 获取实时趋势
	trends, err := client.Realtime(time.Now(), "US", "en-US")
	if err != nil {
		log.Fatal(err)
	}

	for _, trend := range trends {
		fmt.Printf("标题: %s\n", trend.Title)
		fmt.Printf("搜索量: %d\n", trend.Traffic)
		fmt.Println("------------------------")
	}
}

3. 搜索特定关键词的趋势

func searchKeywordTrends() {
	client := gogtrends.NewClient()
	
	// 搜索关键词"Golang"的趋势
	kw := "Golang"
	
	// 获取过去30天的趋势
	now := time.Now()
	monthAgo := now.AddDate(0, -1, 0)
	
	// 设置搜索参数
	params := &gogtrends.SearchParams{
		Keyword: kw,
		Start:   monthAgo,
		End:     now,
		Geo:     "US",
		Lang:    "en-US",
	}
	
	// 获取趋势数据
	trends, err := client.InterestOverTime(params)
	if err != nil {
		log.Fatal(err)
	}

	// 打印结果
	for _, point := range trends {
		fmt.Printf("日期: %s, 热度: %d\n", 
			point.Date.Format("2006-01-02"), 
			point.Value)
	}
}

4. 获取相关查询

func getRelatedQueries() {
	client := gogtrends.NewClient()
	
	params := &gogtrends.SearchParams{
		Keyword: "Bitcoin",
		Start:   time.Now().AddDate(0, -1, 0),
		End:     time.Now(),
		Geo:     "US",
		Lang:    "en-US",
	}
	
	// 获取相关查询
	related, err := client.RelatedQueries(params)
	if err != nil {
		log.Fatal(err)
	}

	// 打印相关查询
	fmt.Println("相关查询:")
	for _, query := range related {
		fmt.Printf("- %s (热度: %d)\n", query.Query, query.Value)
	}
}

高级功能

1. 多关键词比较

func compareKeywords() {
	client := gogtrends.NewClient()
	
	params := &gogtrends.SearchParams{
		Keyword: []string{"Golang", "Python", "Java"},
		Start:   time.Now().AddDate(0, -1, 0),
		End:     time.Now(),
		Geo:     "US",
		Lang:    "en-US",
	}
	
	// 获取比较数据
	comparison, err := client.InterestOverTime(params)
	if err != nil {
		log.Fatal(err)
	}

	// 打印比较结果
	for _, point := range comparison {
		fmt.Printf("日期: %s\n", point.Date.Format("2006-01-02"))
		for kw, value := range point.Values {
			fmt.Printf("  %s: %d\n", kw, value)
		}
	}
}

2. 按地区获取趋势

func trendsByRegion() {
	client := gogtrends.NewClient()
	
	params := &gogtrends.SearchParams{
		Keyword: "Tesla",
		Start:   time.Now().AddDate(0, -1, 0),
		End:     time.Now(),
		Geo:     "US",
		Lang:    "en-US",
	}
	
	// 获取地区趋势
	regions, err := client.InterestByRegion(params, gogtrends.City)
	if err != nil {
		log.Fatal(err)
	}

	// 打印地区趋势
	for _, region := range regions {
		fmt.Printf("%s: %d\n", region.Name, region.Value)
	}
}

注意事项

  1. API限制:Google Trends有请求频率限制,过度请求可能导致暂时封禁
  2. 非官方API:Google可能会随时更改其内部API,导致此库失效
  3. 数据准确性:返回的数据可能与Google Trends网站显示的数据有差异
  4. 代理设置:如果需要代理,可以在创建客户端时配置
client := gogtrends.NewClient(
	gogtrends.WithHTTPClient(&http.Client{
		Transport: &http.Transport{
			Proxy: http.ProxyURL("http://proxy.example.com:8080"),
		},
	}),
)

gogtrends库为Go开发者提供了访问Google Trends数据的便捷方式,适合用于市场研究、趋势分析等场景。使用时请遵守Google的服务条款。

回到顶部