杰瑞科技汇

Python sinaweibopy如何使用?

Of course! sinaweibopy is a popular and mature Python library for interacting with the Sina Weibo (新浪微博) API. It allows developers to perform a wide range of tasks, such as authenticating with Weibo, posting statuses, fetching timelines, managing users, and more.

Python sinaweibopy如何使用?-图1
(图片来源网络,侵删)

Here's a comprehensive guide covering what it is, how to install it, how to authenticate, and how to perform common tasks.


What is sinaweibopy?

sinaweibopy is a third-party, open-source Python wrapper for the Sina Weibo API. It simplifies the process of making API calls by handling the complexities of OAuth 2.0 authentication, request signing, and response parsing. You can interact with Weibo's features using simple Python functions instead of manually crafting HTTP requests.

Key Features:

  • OAuth 2.0 Support: Handles the entire authentication flow.
  • API Coverage: Supports most of the official Weibo API endpoints.
  • Easy to Use: Provides a high-level, intuitive interface.
  • Pythonic: Returns data in standard Python formats like dictionaries and lists.

Prerequisites

Before you start, you need two things from the Sina Weibo open platform:

Python sinaweibopy如何使用?-图2
(图片来源网络,侵删)
  1. Weibo Developer Account: Register as a developer at open.weibo.com.
  2. An App: Create a new application in your developer dashboard. You will get:
    • App Key (API Key): A unique identifier for your app.
    • App Secret (API Secret): A secret key for your app.
    • Redirect URI: A URL where Weibo will send the user after they authorize your app. For development, you can use http://127.0.0.1:8080 or a similar local address.

Installation

You can install sinaweibopy easily using pip:

pip install sinaweibopy

Authentication (OAuth 2.0)

This is the most crucial first step. You need to get an Access Token that allows your script to act on behalf of a Weibo user. The library provides a helper class, OAuth2Handler, to manage this.

Step-by-Step Authentication Flow

Here's how to guide a user through the login process and get the final access token.

import webbrowser
from sinaweibopy import OAuth2Handler, APIClient
# --- 1. Your App Credentials from open.weibo.com ---
# Replace with your actual App Key and Secret
APP_KEY = 'YOUR_APP_KEY'
APP_SECRET = 'YOUR_APP_SECRET'
# The URL where Weibo will redirect the user after authorization.
# This must match one of the Redirect URIs configured in your app settings.
REDIRECT_URI = 'http://127.0.0.1:8080'
# --- 2. Create an OAuth2Handler instance ---
oauth = OAuth2Handler(
    client_id=APP_KEY,
    client_secret=APP_SECRET,
    redirect_uri=REDIRECT_URI
)
# --- 3. Get the Authorization URL ---
# This URL is what the user will visit to log in and grant permission.
auth_url = oauth.get_authorize_url()
print(f"Please visit this URL and authorize the application: {auth_url}")
# --- 4. Open the URL in a web browser ---
webbrowser.open(auth_url)
# --- 5. Get the Authorization Code ---
# After the user authorizes, Weibo will redirect to your REDIRECT_URI.
# The URL will look like: http://127.0.0.1:8080/?code=YOUR_AUTH_CODE
# You need to capture this 'code'.
# In a real web app, you'd get this from a web request handler.
# For a simple script, we'll just print instructions.
print("\nAfter authorizing, the browser will be redirected.")
print("Copy the 'code' parameter from the redirected URL (e.g., http://127.0.0.1:8080/?code=ABC123).")
auth_code = input("Paste the authorization code here: ")
# --- 6. Exchange the Authorization Code for an Access Token ---
try:
    access_token = oauth.request_access_token(auth_code)
    print("\nSuccessfully obtained access token!")
    print(f"Access Token: {access_token['access_token']}")
    print(f"User ID: {access_token['uid']}")
    # The access token is now what you'll use for all API calls.
    # It's good practice to save this token for future use so the user doesn't have to log in every time.
except Exception as e:
    print(f"Error getting access token: {e}")

Note: For production applications, you would not have the user manually copy and paste the code. You would set up a small local web server (e.g., using Flask) to listen on the REDIRECT_URI and automatically capture the code from the incoming request.

Python sinaweibopy如何使用?-图3
(图片来源网络,侵删)

Making API Calls

Once you have the access_token, you can create an APIClient instance to interact with the Weibo API.

from sinaweibopy import APIClient
# Use the access token obtained in the previous step
# For this example, let's assume we have it saved.
# Replace with your actual access token and user ID.
ACCESS_TOKEN = 'YOUR_ACCESS_TOKEN'
USER_ID = 'YOUR_USER_ID' # This is also part of the access token response
# Initialize the APIClient
client = APIClient(
    app_key='YOUR_APP_KEY',
    app_secret='YOUR_APP_SECRET',
    redirect_uri='http://127.0.0.1:8080',
    access_token=ACCESS_TOKEN
)
# --- Example 1: Get User's Timeline (Home Timeline) ---
print("\n--- Fetching Home Timeline ---")
try:
    # The .statuses__home_timeline() method corresponds to the API endpoint:
    # https://open.weibo.com/wiki/2/statuses/home_timeline
    # Parameters are passed as keyword arguments.
    timeline = client.statuses__home_timeline(count=5)
    if timeline:
        for status in timeline:
            print(f"- {status['text']} by {status['user']['screen_name']}")
    else:
        print("No statuses found or an error occurred.")
except Exception as e:
    print(f"Error fetching timeline: {e}")
# --- Example 2: Get Public Timeline ---
print("\n--- Fetching Public Timeline ---")
try:
    public_timeline = client.statuses__public_timeline(count=5)
    if public_timeline:
        for status in public_timeline:
            print(f"- {status['text']} by {status['user']['screen_name']}")
    else:
        print("No statuses found or an error occurred.")
except Exception as e:
    print(f"Error fetching public timeline: {e}")
# --- Example 3: Post a New Status (Weibo) ---
print("\n--- Posting a New Status ---")
# Note: You need 'write' permissions (scope) for this to work.
# These are requested when the user authorizes your app.
try:
    # The .statuses__update() method corresponds to:
    # https://open.weibo.com/wiki/2/statuses/update
    # The 'status' parameter is the text of the weibo.
    new_status = client.statuses__update(status="Hello from Python! Testing sinaweibopy. #Python #WeiboAPI")
    if 'id' in new_status:
        print(f"Successfully posted! Weibo ID: {new_status['id']}")
        print(f"You can view it here: https://weibo.com/{new_status['user']['id']}/{new_status['id']}")
    else:
        print("Failed to post status. Check error message.")
        print(new_status)
except Exception as e:
    print(f"Error posting status: {e}")

Common API Endpoints and Mapping

The APIClient maps API endpoints to Python methods using a double underscore (__) convention.

Official API Endpoint (/2/verb/noun) sinaweibopy Method Call (client.verb__noun()) Description
/2/statuses/home_timeline client.statuses__home_timeline() Get the user's home timeline.
/2/statuses/public_timeline client.statuses__public_timeline() Get the public timeline.
/2/statuses/update client.statuses__update() Post a new status.
/2/users/show client.users__show() Get detailed information for a user.
/2/friendships/create client.friendships__create() Follow a user.
/2/comments/create client.comments__create() Comment on a status.
/2/search/topics client.search__topics() Search for hot topics.

Parameters for the API calls are passed as keyword arguments to the method. For example, to get 10 statuses from a specific user:

user_timeline = client.statuses__user_timeline(uid=USER_ID, count=10, page=1)

Handling Errors

API calls can fail for many reasons (invalid token, rate limits, network issues). The library will often raise a generic Exception or return an error dictionary in the response. Always wrap your API calls in a try...except block.

try:
    # An action that might fail
    result = client.some_api_call(param='value')
except Exception as e:
    # Check the error message for details
    print(f"An API error occurred: {e}")
    # Sometimes the response itself contains an error object
    if hasattr(e, 'args') and e.args:
        print(f"Error details: {e.args[0]}")

Important Considerations

  • Rate Limits: The Weibo API has strict rate limits. If you make too many requests in a short period, you will be temporarily blocked. Always check the documentation for the specific limits of the endpoint you are using.
  • Scopes (Permissions): When you get the authorization URL, you can specify the permissions (or "scopes") your app needs. For example, to be able to post, you need the email and write scopes.
    # To request email and write permissions
    auth_url = oauth.get_authorize_url(scope='email write')
  • Official Documentation: The ultimate source of truth is the Sina Weibo API Documentation. Use it to find all available endpoints, their parameters, and return formats.
  • Alternatives: While sinaweibopy is great, another popular library is weibo. You might find it has a slightly different API or is more actively maintained. It's worth checking out if you run into issues with sinaweibopy. The installation is pip install weibo.
分享:
扫描分享到社交APP
上一篇
下一篇