杰瑞科技汇

Python Twitter API如何调用?

Of course! Using the Python Twitter API is a common task for developers. The process has changed significantly with the introduction of Twitter API v2, which is the modern, recommended way to interact with the platform.

Python Twitter API如何调用?-图1
(图片来源网络,侵删)

This guide will walk you through everything you need to know, from setup to making your first API call, covering the most popular library, tweepy.


The Twitter API Landscape: v1.1 vs. v2

First, it's crucial to understand the difference between the old and new APIs.

Feature Twitter API v1.1 (Legacy) Twitter API v2 (Current)
Endpoint api.twitter.com/1.1/ api.twitter.com/2/
Authentication OAuth 1.0a (for most endpoints) OAuth 2.0 (Bearer Token is simplest)
Data Format JSON JSON
Features Limited, less efficient. Full access to "firehose" (historically). More efficient, modern, and powerful. Focuses on recent data.
Rate Limits Complex, per-endpoint. Simpler, per "app" or "user". More generous for v2.
Recommendation Avoid for new projects. Use only for accessing features not yet available in v2. Use for all new projects. This is the future.

For this guide, we will focus exclusively on Twitter API v2.


Prerequisites: Getting Your API Keys

You cannot use the Twitter API without credentials. Here's how to get them.

Python Twitter API如何调用?-图2
(图片来源网络,侵删)
  1. Apply for a Twitter Developer Account:

    • Go to the Twitter Developer Portal.
    • Sign in with your Twitter account.
    • Apply for a developer account. You'll need to describe your intended use. Be specific! For learning, you can say something like "I am a developer learning to use the Twitter API v2 for personal projects and to understand social media data analysis."
  2. Create a New Project and App:

    • Once your account is approved, you'll be in the Developer Portal Dashboard.
    • Click + Create Project. Give it a name (e.g., "My First Twitter Project") and a use case (select "Student learning to code" or similar).
    • After creating the project, you'll be prompted to create an App. Give your app a name (e.g., "My Python Scraper App").
    • You will be asked how your app will use the Twitter API. Choose "Read and write" for maximum flexibility, though "Read" is often all you need.
  3. Get Your Keys and Tokens:

    • Once your app is created, navigate to your app's "Keys and tokens" section.
    • You will see several credentials. For most v2 interactions, you only need the Bearer Token. This is the simplest form of OAuth 2.0 authentication.
    • IMPORTANT: Copy your Bearer Token immediately. You cannot view it again after you leave the page. Treat it like a password.

Choosing a Python Library

While you can make raw HTTP requests using libraries like requests, it's much easier to use a dedicated wrapper. The most popular and well-maintained library for Twitter API v2 is tweepy.

Python Twitter API如何调用?-图3
(图片来源网络,侵删)

Installation

First, install tweepy using pip:

pip install tweepy

Making Your First API Call (v2)

Let's start with a simple, public endpoint that doesn't require special authentication beyond the Bearer Token: fetching a user's profile.

Step 1: Authenticate

Create a Python file (e.g., twitter_app.py) and add your Bearer Token.

import tweepy
# Replace with your own Bearer Token
BEARER_TOKEN = "YOUR_BEARER_TOKEN_HERE"
# Create a client object
client = tweepy.Client(BEARER_TOKEN)

Step 2: Fetch a User's Profile

The tweepy.Client object has methods that map directly to API v2 endpoints. Let's get the profile for Twitter's official account (@TwitterDev).

import tweepy
# Replace with your own Bearer Token
BEARER_TOKEN = "YOUR_BEARER_TOKEN_HERE"
# Create a client object
client = tweepy.Client(BEARER_TOKEN)
# The username of the account to fetch
username = "TwitterDev"
try:
    # Use the get_user method to fetch user information
    # The `username` parameter specifies the user to look up
    user = client.get_user(username=username)
    # Check if the user was found
    if user.data:
        print(f"User found: {user.data.name}")
        print(f"Username: @{user.data.username}")
        print(f"Description: {user.data.description}")
        print(f"Followers: {user.data.public_metrics['followers_count']}")
    else:
        print(f"User '{username}' not found.")
except Exception as e:
    print(f"An error occurred: {e}")

To run this code:

  1. Replace "YOUR_BEARER_TOKEN_HERE" with the actual token you copied.
  2. Save the file.
  3. Run it from your terminal: python twitter_app.py

You should see output like this:

User found: Twitter Dev
Username: @TwitterDev
Description: Your source for Twitter platform news, developer events, and access to tools to help you build on the platform.
Followers: 5345343

Common Use Cases with tweepy

Here are examples for other common tasks.

A) Searching for Tweets

The v2 search endpoint is powerful and uses the standard query parameter.

import tweepy
BEARER_TOKEN = "YOUR_BEARER_TOKEN_HERE"
client = tweepy.Client(BEARER_TOKEN)
# Search for recent tweets containing "python" and "tweepy"
# The `tweet_fields` parameter lets you specify what data to include
query = "python tweepy -is:retweet" # -is:retweet filters out retweets
tweet_fields = ["author_id", "created_at", "public_metrics"]
try:
    # The search_recent_tweets method is for the last 7 days
    tweets = client.search_recent_tweets(query=query, tweet_fields=tweet_fields, max_results=10)
    if tweets.data:
        print(f"Found {len(tweets.data)} tweets:")
        for tweet in tweets.data:
            print(f"  - @{tweet.author_id}: {tweet.text} (Likes: {tweet.public_metrics['like_count']})")
    else:
        print("No tweets found for this query.")
except Exception as e:
    print(f"An error occurred: {e}")

B) Getting a User's Timeline

To get a user's own tweets (or their public timeline), you need the user's ID.

import tweepy
BEARER_TOKEN = "YOUR_BEARER_TOKEN_HERE"
client = tweepy.Client(BEARER_TOKEN)
# First, get the user ID
username = "TwitterDev"
user_response = client.get_user(username=username)
user_id = user_response.data.id
# Now, fetch the user's tweets using their ID
try:
    # The get_users_tweets method fetches tweets from a specific user
    tweets = client.get_users_tweets(id=user_id, max_results=5)
    if tweets.data:
        print(f"Recent tweets from @{username}:")
        for tweet in tweets.data:
            print(f"  - {tweet.text}")
    else:
        print("No tweets found for this user.")
except Exception as e:
    print(f"An error occurred: {e}")

Important Considerations

A) Rate Limits

The Twitter API limits how many requests you can make in a 15-minute window to prevent abuse. tweepy helps with this by automatically detecting rate limit headers and waiting for you if you exceed the limit.

You can check your rate limit status like this:

# Check the rate limit status for the search endpoint
rate_limit_data = client.get_rate_limit_limits()
print(rate_limit_data)

B) Academic Research Product (ARP)

If you are a researcher, you can apply for the Academic Research Product. This gives you access to the full public archive of tweets (back to 2006) and higher rate limits, which is essential for serious research. The application process is more rigorous.

C) OAuth 2.0 Authorization Code Flow (For Posting Tweets)

The Bearer Token is great for reading data, but you cannot use it to post tweets or perform other write operations. For that, you need to use the full OAuth 2.0 Authorization Code flow. This is more complex as it involves redirecting a user to a Twitter login page to grant your app permission.

Here's a conceptual overview:

  1. In your App settings on the Developer Portal, you must enable "OAuth 2.0 Authorization Code Flow with PKCE".
  2. Redirect URL: Add a local redirect URL (e.g., http://127.0.0.1:8000/auth/callback/).
  3. In your Python code:
    • You'll generate a code_verifier and code_challenge.
    • Redirect the user to Twitter's authorization URL.
    • The user logs in and approves your app.
    • Twitter redirects them back to your redirect URL with a code.
    • Your server exchanges this code for an access_token and refresh_token.
    • You use the access_token to make authenticated write requests.

This is beyond the scope of a simple "getting started" guide, but it's the next step if you need to post tweets, like, or retweet on behalf of a user.


Summary and Further Learning

  1. Use Twitter API v2 for all new projects.
  2. Get a Bearer Token from the Twitter Developer Portal.
  3. Use the tweepy library to simplify API interactions.
  4. Start with tweepy.Client(BEARER_TOKEN) for read-only operations.
  5. Be mindful of rate limits.
  6. For writing (posting, etc.), you'll need to implement the more complex OAuth 2.0 Authorization Code Flow.

Excellent Resources:

分享:
扫描分享到社交APP
上一篇
下一篇