如何通过rtweet批量获取多个Twitter用户的粉丝列表?
Great question! I’ve run into this exact scenario with rtweet before—while get_followers() only accepts one user per direct call, there are straightforward ways to batch process your 155 accounts. Let’s walk through the best approaches:
Batch Fetch Followers with rtweet
1. Basic For Loop Approach
The simplest way is to iterate over your list of users with a for loop, fetching followers one at a time and storing the results. This is easy to read and debug:
# Load the rtweet package library(rtweet) # Replace this with your actual list of 155 user screen names/IDs target_users <- c("user1", "user2", "user3", ...) # Initialize an empty list to store results for each user follower_results <- list() # Loop through each user for (i in seq_along(target_users)) { current_user <- target_users[i] cat("Fetching followers for", current_user, "...\n") # Fetch followers, use retryonratelimit to handle API limits automatically user_followers <- get_followers( user = current_user, retryonratelimit = TRUE ) # Add a column to track which user these followers belong to user_followers$source_user <- current_user # Store the result in our list follower_results[[i]] <- user_followers } # Combine all results into a single data frame all_followers <- do.call(rbind, follower_results)
2. Tidyverse-Friendly purrr Approach
If you prefer a more concise, functional programming style, use purrr::map_dfr to automatically bind results into a single data frame:
library(rtweet) library(purrr) library(dplyr) target_users <- c("user1", "user2", ...) # Use map_dfr to iterate and bind results all_followers <- map_dfr(target_users, function(user) { cat("Processing", user, "\n") get_followers(user, retryonratelimit = TRUE) %>% mutate(source_user = user) # Add source user identifier })
Critical Tips for Success
- Rate Limit Handling: Twitter’s API restricts follower requests to 15 calls per 15-minute window. The
retryonratelimit = TRUEargument is non-negotiable here—it makes rtweet automatically pause and resume when you hit limits, instead of throwing errors. - Error Resilience: Some users might be private, suspended, or have zero followers. Wrap the
get_followerscall intryCatchto avoid breaking your entire batch:# Example with error handling in a loop for (i in seq_along(target_users)) { current_user <- target_users[i] cat("Fetching followers for", current_user, "...\n") tryCatch({ user_followers <- get_followers(current_user, retryonratelimit = TRUE) user_followers$source_user <- current_user follower_results[[i]] <- user_followers }, error = function(e) { cat("Failed to fetch followers for", current_user, ":", e$message, "\n") follower_results[[i]] <- NULL # Mark failed entries }) } - Save Intermediate Progress: With 155 users, processing could take hours. Save your list of results periodically with
saveRDS(follower_results, "follower_progress.RDS")to avoid losing work if your session crashes.
内容的提问来源于stack exchange,提问作者Waqas Chaudhary
相关产品推荐
相关产品推荐

