使用具有免费级别访问权限的 Tweepy 访问 Twitter API 时出现问题

问题描述 投票:0回答:1

我使用

tweepy
实现了一个 Python 脚本来获取用户最新的推文并将其保存到 Excel 文件中。这是我的代码的简化版本:

import tweepy
import pandas as pd

# My Twitter API credentials
API_KEY = 'x'
API_SECRET_KEY = 'x'
ACCESS_TOKEN = 'xx'
ACCESS_TOKEN_SECRET = 'xxxx'

# Authentication with tweepy
auth = tweepy.OAuthHandler(API_KEY, API_SECRET_KEY)
auth.set_access_token(ACCESS_TOKEN, ACCESS_TOKEN_SECRET)
api = tweepy.API(auth)

def get_tweets(username, count=200):
    tweets = api.user_timeline(screen_name=username, count=count, tweet_mode="extended")
    tweet_data = [{
        'tweet_id': tweet.id,
        'created_at': tweet.created_at,
        'text': tweet.full_text,
        'likes': tweet.favorite_count,
        'retweets': tweet.retweet_count
    } for tweet in tweets]
    return tweet_data

def main():
    user = 'x'
    data = get_tweets(user, count=200)

    df = pd.DataFrame(data)
    df.to_excel('twitter_data.xlsx', index=False)

if __name__ == "__main__":
    main()

但是,我在运行脚本时遇到以下错误:

453 - You currently have access to a subset of Twitter API v2 endpoints and limited v1.1 endpoints (e.g. media post, oauth) only. If you need access to this endpoint, you may need a different access level. You can learn more here: https://developer.twitter.com/en/portal/product

值得注意的是,我目前处于 Twitter API 的免费级别访问权限。

我是否需要升级访问权限才能使用此端点,或者是否有其他解决方案来使用免费级别访问权限访问数据?

python pandas twitter tweepy
1个回答
0
投票

您似乎正在使用 Twitter API v1.1,它不再支持 搜索最近的推文 功能。

您必须利用 Twitter API v2 才能使用相同的功能,但它需要 基本级别访问

示例:

# Authenticate to Twitter
client = tweepy.Client(
    consumer_key=CONSUMER_KEY,
    consumer_secret=CONSUMER_SECRET,
    access_token=ACCESS_TOKEN,
    access_token_secret=ACCESS_TOKEN_SECRET
)

# Search Tweets
query = "Twitter"
max_tweets = 100
searched_tweets = tweepy.Paginator(client.search_recent_tweets, query=query, max_results=max_tweets).flatten(limit=max_tweets)

如果您计划检索一次最多 100 条推文,那么您不需要分页

因此,您可以使用以下代码行:

searched_tweets = client.search_recent_tweets(query=query, max_results=max_tweets)

欲了解更多信息:

https://developer.twitter.com/en/docs/twitter-api

https://docs.tweepy.org/en/stable/client.html#tweepy.Client.search_recent_tweets

https://docs.tweepy.org/en/latest/v2_pagination.html

我希望这有帮助。

© www.soinside.com 2019 - 2024. All rights reserved.