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

使用Twitter V1 API搜索推文遇JSON解析失败问题求助

解决建议

1. 确认API端点权限与可用性

Twitter API v1.1的search/tweets端点(对应Tweepy的search_tweets方法)需要标准搜索API权限,若你的开发者账号权限被调整,或该端点访问规则变更,可能返回非JSON格式的无效响应:

  • 登录Twitter开发者平台,检查项目/应用是否仍拥有Standard Search API的访问权限;
  • 注意:Twitter正逐步推进API v2,v1.1的部分搜索功能可能被限制或停用。

2. 调试原始API响应

添加代码捕获并打印原始响应,确认返回内容是否为有效JSON:

import tweepy
from tweepy import TweepyException

consumer_key = "*"
consumer_secret = "*"
access_key = "*"
access_secret = "*"

def get_init_tweets(screen_name):
    auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
    auth.set_access_token(access_key, access_secret)
    api = tweepy.API(auth, wait_on_rate_limit=True)
    try:
        print(api.verify_credentials().screen_name)
        # 手动发起请求查看原始响应
        raw_response = api.request('GET', 'search/tweets', 
                                   {'q': '@ElonMuskAOC', 'count': 200, 'result_type': 'recent'})
        print("状态码:", raw_response.status_code)
        print("原始响应内容:", raw_response.text)
        new_tweets = api.search_tweets(q='@ElonMuskAOC', count=200, result_type='recent')
        return new_tweets
    except TweepyException as e:
        print(f"错误详情: {e}")
        return None

如果返回403/404状态码,说明权限不足或端点不可用;若返回HTML内容,说明请求被重定向到错误页面。

3. 调整参数与更新Tweepy

  • 移除result_type='recent'参数:该参数在v1.1部分场景下已被弃用,尝试使用默认的混合结果模式;
  • 更新Tweepy到最新版本,旧版本可能不兼容API端点的变更:
pip install --upgrade tweepy

4. 迁移到Twitter API v2

由于v1.1功能逐步被淘汰,建议切换到v2 API的搜索端点,Tweepy已支持v2:

client = tweepy.Client(
    bearer_token="你的Bearer Token",
    consumer_key=consumer_key,
    consumer_secret=consumer_secret,
    access_token=access_key,
    access_token_secret=access_secret,
)

# 调用v2的最新推文搜索接口
response = client.search_recent_tweets(query='@ElonMuskAOC', max_results=200)
tweets = response.data
if tweets:
    for tweet in tweets:
        print(tweet.text)

注意:使用v2 API需在开发者平台申请对应权限,并配置Bearer Token。

5. 排查网络环境

部分网络环境可能拦截API请求,导致返回空响应或错误内容。尝试切换网络(如代理、不同的网络环境),确认是否为网络问题导致无法获取有效JSON。


内容的提问来源于stack exchange,提问作者Harsh Bhatnagar

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.14 01:52:38