2013-12-02 2 views
3

Я пытаюсь загрузить данные Google Trends в формате csv. Для основных запросов я был успешным (после blog post от Кристофа Ридля).Пытается загрузить данные Google Trends, но параметр даты игнорируется?

Задача: По умолчанию тенденции возвращаются с января 2004 года. Я бы предпочел, чтобы они возвращали тенденции, начиная с января 2011 года. Однако, когда я добавляю параметр даты в запрос URL-адреса, он полностью игнорируется. Я не уверен, как это преодолеть.

Следующий код воспроизведет проблему.

# Just copy/paste this stuff - these are helper functions 
require(RCurl) 

# This gets the GALX cookie which we need to pass back with the login form 
getGALX <- function(curl) { 
    txt = basicTextGatherer() 
    curlPerform(url=loginURL, curl=curl, writefunction=txt$update, header=TRUE, ssl.verifypeer=FALSE) 

    tmp <- txt$value() 

    val <- grep("Cookie: GALX", strsplit(tmp, "\n")[[1]], val = TRUE) 
    strsplit(val, "[:=;]")[[1]][3] 

    return(strsplit(val, "[:=;]")[[1]][3]) 
} 

# Function to perform Google login and get cookies ready 
gLogin <- function(username, password) { 
    ch <- getCurlHandle() 

    ans <- (curlSetOpt(curl = ch, 
        ssl.verifypeer = FALSE, 
        useragent = getOption('HTTPUserAgent', "R"), 
        timeout = 60,   
        followlocation = TRUE, 
        cookiejar = "./cookies", 
        cookiefile = "")) 

    galx <- getGALX(ch) 
    authenticatePage <- postForm(authenticateURL, .params=list(Email=username, Passwd=password, GALX=galx, PersistentCookie="yes", continue="http://www.google.com/trends"), curl=ch) 

    authenticatePage2 <- getURL("http://www.google.com", curl=ch) 

    if(getCurlInfo(ch)$response.code == 200) { 
    print("Google login successful!") 
    } else { 
    print("Google login failed!") 
    } 
    return(ch) 
} 

# returns string w/o leading or trailing whitespace 
trim <- function (x) gsub("^\\s+|\\s+$", "", x) 

get_interest_over_time <- function(res, clean.col.names = TRUE) { 
    # remove all text before "Interest over time" data block begins 
    data <- gsub(".*Interest over time", "", res) 

    # remove all text after "Interest over time" data block ends 
    data <- gsub("\n\n.*", "", data) 

    # convert "interest over time" data block into data.frame 
    data.df <- read.table(text = data, sep =",", header=TRUE) 

    # Split data range into to only end of week date 
    data.df$Week <- gsub(".*\\s-\\s", "", data.df$Week) 
    data.df$Week <- as.Date(data.df$Week) 

    # clean column names 
    if(clean.col.names == TRUE) colnames(data.df) <- gsub("\\.\\..*", "", colnames(data.df)) 

    # return "interest over time" data.frame 
    return(data.df) 
} 

В браузере, пожалуйста, войдите в систему Google (например, войдите в систему gmail). В R выполните следующее:

# Username and password 
username <- "[email protected]" 
password <- "password" 

# Login and Authentication URLs 
loginURL  <- "https://accounts.google.com/accounts/ServiceLogin" 
authenticateURL <- "https://accounts.google.com/accounts/ServiceLoginAuth" 
trendsURL  <- "http://www.google.com/trends/TrendsRepport?" 

# Google authentication 
ch <- gLogin(username, password) 
authenticatePage2 <- getURL("http://www.google.com", curl=ch) 

следующие успешно возвращает Google данные тенденции с января 2004 года (т.е. без параметров даты)

res <- getForm(trendsURL, q="ggplot2, ggplot", content=1, export=1, graph="all_csv", curl=ch) 
df <- get_interest_over_time(res) 
head(df) 

     Week ggplot2 ggplot 
1 2004-01-10  0  0 
2 2004-01-17  0  0 
3 2004-01-24  0  0 
4 2004-01-31  0  0 
5 2004-02-07  0  0 
6 2004-02-14  0  0 

ОДНАКО, добавив параметр даты, чтобы вернуть тенденции, начиная с января 2013 года игнорируется

res <- getForm(trendsURL, q="ggplot2, ggplot", date = "1/2013 11m", content=1, export=1, graph="all_csv", curl=ch) 
df <- get_interest_over_time(res) 
head(df) 

     Week ggplot2 ggplot 
1 2004-01-10  0  0 
2 2004-01-17  0  0 
3 2004-01-24  0  0 
4 2004-01-31  0  0 
5 2004-02-07  0  0 
6 2004-02-14  0  0 

ПРИМЕЧАНИЕ 1: То же самое происходит с параметром cat = category. Выше это просто проще показать с датой.

ПРИМЕЧАНИЕ 2: Поскольку Google пересканирует данные в зависимости от даты начала, это не случай простой фильтрации data.frame. Меня интересует, почему параметр даты игнорируется.

Благодарим вас за ваше время.

ответ

1

Это работает, если вы пишете только год:

res <- getForm(trendsURL, q="ggplot2, ggplot", date = "2013", content=1, export=1, graph="all_csv", curl=ch) 

Но я не знаю, как добавить месяц и день в день. Возможно, это происходит потому, что на веб-странице GoogleTrends вы можете выбрать диапазон времени из списка:

«Прошедшие 7 дней», «За последние 30 дней», ..., «2013», «2012», ...

Но если я попробую date="Past 90 days", он все еще не работает.

1

У меня было успешное получение ежемесячных данных с использованием спецификации даты date="2011-1" (январь 2011 г.). Я просмотрел источник за страницей - возможно, вы можете найти там участников.

Повторите попытку, если вы определили спецификацию даты.

+0

@Tony Breyal: есть ли у вас какие-либо успехи, указывающие интервалы времени? – Sunv

+0

@Tonybreyal: есть ли у вас какие-либо обновления в отношении спецификации интервалов дат? – Sunv

Смежные вопросы