首页 > 解决方案 > 通过 R 下载谷歌趋势数据

问题描述

我正在使用这个脚本从谷歌趋势下载数据。但是,它不会打印过去 3 天。换句话说,我在 2020 年 9 月 28 日之前得到了结果,现在是 2020 年 1 月 10 日。

有没有办法下载更新的数据?

谢谢你。

注意:脚本是从这里检索的。

 library(gtrendsR)
    library(tidyverse)
    library(lubridate)

get_daily_gtrend <- function(keyword = 'Taylor Swift', geo = 'UA', from = '2013-01-01', to = '2019-08-15') {
  if (ymd(to) >= floor_date(Sys.Date(), 'month')) {
    to <- floor_date(ymd(to), 'month') - days(1)
    
    if (to < from) {
      stop("Specifying \'to\' date in the current month is not allowed")
    }
  }

  mult_m <- gtrends(keyword = keyword, geo = geo, time = paste(from, to))$interest_over_time %>%
    group_by(month = floor_date(date, 'month')) %>%
    summarise(hits = sum(hits)) %>%
    mutate(ym = format(month, '%Y-%m'),
           mult = hits / max(hits)) %>%
    select(month, ym, mult) %>%
    as_tibble()
  
  pm <- tibble(s = seq(ymd(from), ymd(to), by = 'month'), 
               e = seq(ymd(from), ymd(to), by = 'month') + months(1) - days(1))
  
  raw_trends_m <- tibble()
  
  for (i in seq(1, nrow(pm), 1)) {
    curr <- gtrends(keyword, geo = geo, time = paste(pm$s[i], pm$e[i]))
    print(paste('for', pm$s[i], pm$e[i], 'retrieved', count(curr$interest_over_time), 'days of data'))
    raw_trends_m<- rbind(raw_trends_m,
                         curr$interest_over_time)
  }
  
  trend_m <- raw_trends_m %>%
    select(date, hits) %>%
    mutate(ym = format(date, '%Y-%m')) %>%
    as_tibble()
  
  trend_res <- trend_m %>%
    left_join(mult_m, by = 'ym') %>%
    mutate(est_hits = hits * mult) %>%
    select(date, est_hits) %>%
    as_tibble() %>%
    mutate(date = as.Date(date))
  
  return(trend_res)
}

get_daily_gtrend(keyword = 'Taylor Swift', geo = 'UA', from = '2013-01-01', to = '2019-08-15')

标签: rgtrendsr

解决方案


这就是谷歌趋势数据的工作方式。即使您访问该网站并下载过去 7 天到过去 90 天内的任何数据,它也会为您提供最多三天前的每日数据。所以这是设计使然。我不确定 gTrendsR 是否检索每小时数据,但您可以从网站手动检索过去 7 天的数据,以便在您请求前几个小时获取每小时数据,或者使用 PyTrends 包,它可以每小时返回日期。如果你有每小时的数据,你当然可以很容易地把它聚合到每天。


推荐阅读