You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python使用Tweepy调用Twitter API时循环无法获取下一条Tweet如何解决

问题原因

  • 核心错误是你在for循环内部嵌套了没有终止条件的while True:外层迭代器拿到第一条推文后,会进入内层死循环反复处理同一条推文,永远不会退出内层循环回到外层迭代器取下一条内容。
  • StopIteration是外层迭代器耗尽时抛出的异常,你在内层逻辑中捕获完全无法生效。
  • 你提前定义的r、c两个Cursor迭代对象没有被使用,重复创建了新的Cursor实例,属于冗余代码。
  • 补充:你当前的回复逻辑没有携带被回复用户的@标识,大概率会被Twitter接口判定为非法回复,抛出403 Forbidden错误。

修正后的代码

import time
import random
import tweepy

# 认证逻辑保留不变
auth = tweepy.OAuthHandler(consumerkey, consumerkey_secret)
auth.set_access_token(acesstoken, acesstoken_secret)
api = tweepy.API(auth, wait_on_rate_limit=True)

# 直接使用迭代器遍历即可
tweet_iterator = tweepy.Cursor(api.search_tweets, lista_frases).items(razao_responder)

while True:
    try:
        tweet = next(tweet_iterator)
        # 日期判断逻辑保留
        if int(tweet.created_at.strftime('%d%m%Y')) >= date_int:
            time.sleep(random.randint(time_init, time_final))
            print(f'\nTweet respondido de {tweet.user.screen_name}\nTweet ID: {tweet.id}\nTweet date: {tweet.created_at.strftime("%d/%m/%Y")}')
            # 回复必须@目标用户,否则Twitter会拒绝该回复请求
            reply_content = f"@{tweet.user.screen_name} {lista_respostas[0][1:]}"
            api.update_status(reply_content, in_reply_to_status_id=tweet.id)
    except tweepy.Forbidden as e:
        print(f"权限错误:{e},跳过当前推文")
        continue
    except StopIteration:
        print('No more tweets')
        break
    # 捕获其他非致命异常,避免单条推文错误导致整个程序终止
    except Exception as e:
        print(f"处理推文时发生未知错误:{e},跳过当前推文")
        continue

修改说明

  • 移除了原逻辑中的嵌套死循环,改用直接迭代Cursor迭代器的方式,每次调用next()都会取下一条符合条件的推文
  • 调整了异常捕获的层级,可正确捕获迭代器耗尽的StopIteration信号终止程序
  • 修复了回复逻辑的参数问题,添加了目标用户@标识,避免无意义的403错误
  • 增加了通用异常捕获,单条推文处理失败不会中断整个遍历流程

内容的提问来源于stack exchange,提问作者Pedro Lucas

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.24 22:24:10