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

运行代码时遇tweepy错误:OAuthHandler不存在及tweepy.auth未找到

Fixing Tweepy's AttributeError: 'module' has no attribute 'OAuthHandler' & ImportError: No module named 'tweepy.auth'

Hey there! Those errors pop up because you're likely using Tweepy 2.0 or later—a version that completely revamped how authentication works, ditching the old OAuthHandler class and tweepy.auth module entirely. Let's walk through two solid fixes:

Option 1: Downgrade Tweepy to a version that supports the old auth code

If you want to keep your existing code without changes, roll back to Tweepy 1.14.0 (the last major release before the v2 overhaul). Run this command in your terminal:

pip install tweepy==1.14.0

Once installed, your original code using tweepy.OAuthHandler and imports from tweepy.auth should work as expected.

Option 2: Update your code to match Tweepy v2+'s new auth system

If you want to stick with the latest Tweepy version (recommended for access to Twitter API v2 features), here's how to adjust your authentication code:

For Twitter API v1.1 (still supported in v2+)

Replace OAuthHandler with OAuth1UserHandler—no need to import from tweepy.auth anymore, it's directly available in the main tweepy module:

import tweepy

# New auth class replacing OAuthHandler
auth = tweepy.OAuth1UserHandler(
    consumer_key="YOUR_CONSUMER_KEY",
    consumer_secret="YOUR_CONSUMER_SECRET",
    access_token="YOUR_ACCESS_TOKEN",
    access_token_secret="YOUR_ACCESS_TOKEN_SECRET"
)

# Initialize the API like before
api = tweepy.API(auth)

For Twitter API v2 (newer, more feature-rich)

If you're working with Twitter's latest API v2, use the Client class instead—it handles authentication directly:

import tweepy

client = tweepy.Client(
    bearer_token="YOUR_BEARER_TOKEN",
    consumer_key="YOUR_CONSUMER_KEY",
    consumer_secret="YOUR_CONSUMER_SECRET",
    access_token="YOUR_ACCESS_TOKEN",
    access_token_secret="YOUR_ACCESS_TOKEN_SECRET"
)

# Example: Fetch a user's timeline
response = client.get_users_tweets(id="YOUR_USER_ID")

Just double-check that you're using the right credentials for your API version, and you should be good to go!

内容的提问来源于stack exchange,提问作者Fernando Magdalena

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.19 09:23:51