【问题标题】:Connect to the Twitter Streaming API using R使用 R 连接到 Twitter 流 API
【发布时间】:2012-01-04 19:59:41
【问题描述】:

我刚开始使用 Twitter Streaming API 并使用命令行,使用以下命令将原始 JSON 响应重定向到文件:

curl https://stream.twitter.com/1/statuses/sample.json -u USER:PASSWORD -o "somefile.txt"

是否可以完全留在 R 中并利用 RCurl 来做同样的事情?我想解析每个返回的响应,而不是将输出保存到文件中。我过去曾解析过 twitter 搜索结果,但我想在收到每个响应时都这样做。本质上,对每个 JSON 响应应用一个函数。

提前致谢。

编辑:这是我在 R 中尝试过的代码(不幸的是,我在 Windows 上)。我需要包含对 .pem 文件的引用以避免错误。但是,代码只是“运行”,我似乎看不到返回的内容。我尝试过 print、cat 等。

download.file(url="http://curl.haxx.se/ca/cacert.pem", destfile="cacert.pem")
getURL("https://stream.twitter.com/1/statuses/sample.json", 
       userpwd="USER:PWD",
       cainfo = "cacert.pem")

【问题讨论】:

  • 是的,你可以用命令行 curl 做的任何事情都可以用 RCurl 做。为什么不包括您已经尝试过的代码?
  • 尝试 getURL 函数时,我收到 HTTP 401 错误。这是我相信用户名密码错误的结果。
  • 对于 RCurl SSL 问题,请参阅这篇文章stackoverflow.com/questions/6736895/using-rcurl-with-https/…

标签: r curl twitter


【解决方案1】:

我能够弄清楚基础知识,希望这会有所帮助。

#==============================================================================
# Streaming twitter using RCURL
#==============================================================================
library(RCurl)
library(rjson)

# set the directory
setwd("C:\\")

#### redirects output to a file
WRITE_TO_FILE <- function(x) {

     if (nchar(x) >0 ) {
          write.table(x, file="Twitter Stream Capture.txt", append=T, row.names=F, col.names=F)
     }

}

### windows users will need to get this certificate to authenticate
download.file(url="http://curl.haxx.se/ca/cacert.pem", destfile="cacert.pem")

### write the raw JSON data from the Twitter Firehouse to a text file
getURL("https://stream.twitter.com/1/statuses/sample.json", 
       userpwd=USER:PASSWORD,
       cainfo = "cacert.pem", 
       write=WRITE_TO_FILE)

【讨论】:

    【解决方案2】:

    尝试 R 的 twitter api 包。

    install.packages('twitteR')
    library(twitteR)
    

    我想这就是你需要的。

    【讨论】:

    • 谢谢。我喜欢推特包。这是访问 API 的许多功能的好方法。目前,它不处理对流媒体内容的访问。
    猜你喜欢
    • 2013-05-19
    • 2021-09-13
    • 2016-02-03
    • 2019-04-18
    • 2016-09-12
    • 2015-11-19
    • 2011-09-05
    • 1970-01-01
    • 2015-10-19
    相关资源
    最近更新 更多