Scripting userTimeline from twitteR package to data mine from a list of users in Twitter, accounting for missing users in a list

99封情书 提交于 2020-01-06 10:53:36

问题


I am attempting to compile a corpus of the usertimelines of a specific sub-set of Twitter users. My problem is that in the existing code (given below), when a user's account has been suspended or deleted, the code breaks, giving the provided output & error (below).

   ## ORIGINAL ##
   for (user in users){

  # Download user's timeline from Twitter
  tweets <- userTimeline(user)

  # Extract tweets
  tweets <- unlist( lapply(tweets, function(t) t$getText() ) )

  # Save tweets to file
  write.csv(tweets, file=paste(user, ".csv", sep=""), row.names=F)
  #Sys.sleep(sleepTime)
}

[1] "Not Found" Error in twInterfaceObj$doAPICall(cmd, params, method, ...) : Error: Not Found

My question is, how can I keep the script running, saving some sort of null result for the 'missing' (deleted/inactive) accounts?

I am using the twitteR package in R: ftp://cran.r-project.org/pub/R/web/packages/twitteR/twitteR.pdf

   #EDIT#
# Extract tweets
# Pause for 60 sec
sleepTime = 60

for (user in users) 
{
  # tell the loop to skip a user if their account is protected 
  # or some other error occurs  
  result <- try(userTimeline(user), silent = TRUE);
  if(class(result) == "try-error") next;
  # Download user's timeline from Twitter
  tweets <- userTimeline(user)

  # Extract tweets
  tweets <- unlist( lapply(tweets, function(t) t$getText() ) )

  # Save tweets to file
  write.csv(tweets, file=paste(user, ".csv", sep=""), row.names=F)

  # Tell the loop to pause for 60s between iterations to avoid exceeding the Twitter API request limit
  print('Sleeping for 60 seconds...')
  Sys.sleep(sleepTime); 
}
#
# Now inspect tweets to see the user's timeline data

回答1:


You can catch the exception. see ?try or ?tryCatch. For example:

 tweets <- try(userTimeline(user),silent=TRUE)
 if(inherits(tweets ,'try-error')) 
   return(NULL)
 else{
    ## process normally here  
 }


来源:https://stackoverflow.com/questions/22257857/scripting-usertimeline-from-twitter-package-to-data-mine-from-a-list-of-users-in

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!