获取指定Twitter账号时段内推文、转推及点赞数的代码验证与修正
代码验证与修正
原代码存在的问题
- 转推统计逻辑错误:原代码通过
tweet.retweetCount > 0统计转推数量,实际统计的是「该账号推文被他人转推过的条数」,而非「该账号主动转发他人内容的条数」。 - 全局变量依赖:
start_time和end_time作为全局变量,导致函数复用性差,无法灵活适配不同时间范围的查询。 - HTML转义字符残留:代码中的
>是HTML转义字符,应替换为Python原生的比较运算符>。
修正后的代码
import datetime import snscrape.modules.twitter as sntwitter def get_tweets_retweets_likes(username, start_time, end_time): # 构建Twitter搜索查询语句,获取指定账号在时间范围内的所有推文 search_query = f"from:{username} since:{start_time.strftime('%Y-%m-%d')} until:{end_time.strftime('%Y-%m-%d')}" tweets = sntwitter.TwitterSearchScraper(search_query).get_items() # 初始化统计变量 total_tweets = 0 # 账号发布的总推文数(原创+转推) account_retweets = 0 # 账号主动转发他人内容的条数 total_likes = 0 # 所有推文获得的总点赞数 for tweet in tweets: total_tweets += 1 total_likes += tweet.likeCount # 判断当前推文是否为该账号转发的内容 if tweet.retweetedTweet is not None: account_retweets += 1 return total_tweets, account_retweets, total_likes if __name__ == "__main__": # 定义时间范围 start_time = datetime.datetime(2023, 6, 18, 0, 0, 0) end_time = datetime.datetime(2023, 6, 23, 0, 0, 0) # 从链接提取用户名 twitter_link = "https://twitter.com/elonmusk?s=20" username = twitter_link.split('/')[-1].split('?')[0] # 获取统计数据 total_tweets, account_retweets, total_likes = get_tweets_retweets_likes(username, start_time, end_time) # 打印结果 print(f"时间范围: {start_time} 至 {end_time}") print(f"总推文数(原创+转推): {total_tweets}") print(f"账号主动转推数: {account_retweets}") print(f"所有推文总点赞数: {total_likes}")
关键修正说明
- 转推统计修正:通过
tweet.retweetedTweet is not None判断推文是否为该账号的转推内容,准确统计账号主动转发的条数。 - 函数参数优化:将
start_time和end_time作为函数参数传入,提升函数的复用性和灵活性。 - 变量命名优化:使用更具语义的变量名,增强代码可读性。
- 时间范围说明:snscrape的
until参数为左闭右开区间,until:2023-06-23会获取到2023-06-22 23:59:59之前的推文,符合原代码的时间范围需求。
内容的提问来源于stack exchange,提问作者Mashi De Alwis
相关产品推荐
相关产品推荐

