7

我创建了一个循环,该循环贯穿 Twitter 句柄的向量,并使用包中的search_tweets函数从它们收集推文rtweet

下载最新版本的 rtweet

## install devtools package if it's not already
if (!requireNamespace("devtools", quietly = TRUE)) {
install.packages("devtools")
}

## install dev version of rtweet from github
devtools::install_github("mkearney/rtweet")

library(rtweet)

创建令牌

## autheticate via web browser
token=create_token(
app = "My_app",
consumer_key = "My Consumer Key",
consumer_secret = 
"My Secret Code",set_renv = FALSE)

这是我的 Twitter 句柄,存储在矢量中

twitter_handles=c("@realDonaldTrump","@HillaryClinton","@MittRomney")

然后我遍历这些句柄,并将每个句柄的结果存储为唯一的数据帧

#Loop through the twitter handles & store the results as individual dataframes
for(handle in twitter_handles) {

  result <- search_tweets(handle, n = 3500 , include_rts = FALSE,retryonratelimit = TRUE)

if(length(result) != 0){

  result$`Twitter Handle` <- handle
  result$Source <- "Search"

  df_name <- paste(tolower(substring(handle, 2)),"_search")

  if(exists(df_name)) {
    assign(df_name, unique(rbind(get(df_name), result)))
  } else {
    assign(df_name, result)
  }
  }

  }

但是,当我这样做时,我收到一条错误消息

警告:32 - 无法验证您的身份。向量中的错误(“列表”,ntimes):无效的“长度”参数

但是我不认为这是一个身份验证问题,因为当我尝试使用随机关键字/主题标签时,我会得到结果

data <- search_tweets("#rstats", n = 10, include_rts = FALSE,token = token)

我的循环工作正常,但最近它开始抛出错误。关于为什么会发生这种情况以及是否有解决方法的任何想法?

非常感谢您的帮助!

4

1 回答 1

3

在第一个错误上:

“警告:32 - 无法对您进行身份验证。向量中的错误(“列表”,ntimes):无效的“长度”参数”

通常,如果您使用的是旧版本的rtweet ,您会遇到此错误。

为什么?

当 Twitter 更新他们的 API 时,他们有时会改变 API GET 请求的结构。每次发生这种情况时, rtweet都必须重新格式化他们的请求,要求您使用最新版本的rtweet来保持与 Twitter API 的连接。有趣的是,一些 API 调用仍然会成功,因为这些对 Twitter API 的调用没有改变。

您遇到的错误引用了@ TwitterCommunity.com

获取最新版本的rtweet

要获取最新版本的rtweet,您可以使用devtools包(安装后)。

## install devtools package if it's not already
if (!requireNamespace("devtools", quietly = TRUE)) {
  install.packages("devtools")
}

## install dev version of rtweet from github
devtools::install_github("mkearney/rtweet")

## load rtweet package
library(rtweet)

相关错误

向量中的错误(“列表”,n.times):无效的“长度”参数另外:警告消息:超出速率限制。

查找跟踪错误的好地方是 github 上的 rtweet 包的 Github 包跟踪列表。

代币安全

这是一个旁白,但我的感觉是您可能还想在没有 API 密钥的情况下共享您的完整代码。您可以在 R 中使用~/.Reviron.

# Reload .Renviron
# Do this to capture any edits to Environment variables
readRenviron("~/.Renviron")

# Generate a token
token <- create_token(
  app = "rtweet_51672443_test_application",
  consumer_key = Sys.getenv("RTWEET_CONSUMER_KEY"),
  consumer_secret = Sys.getenv("RTWEET_CONSUMER_SECRET_KEY")
) 

其中 .Renviron 包含:

RTWEET_CONSUMER_KEY="<Insert Consumer Key obtained from Titter>"
RTWEET_CONSUMER_SECRET_KEY="<Insert Consumer Secret Key obtained from Titter>"

我希望以上内容可以帮助您指出正确的方向。

于 2018-08-14T17:14:49.603 回答