问题
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