杰瑞科技汇

Python如何获取QzoneToken?

Of course. Let's break down how to get a Qzone token in Python.

Python如何获取QzoneToken?-图1
(图片来源网络,侵删)

Understanding the Concept: Qzone Token

First, it's crucial to understand what a "Qzone token" is. Qzone is Tencent's social network service, heavily integrated with its other services like QQ. A "token" is a piece of data that proves your identity and grants you permission to perform actions on behalf of a user.

There are two primary types of tokens you might be interested in:

  1. Login Token (Session Cookie): This is the most common type. It's what your browser uses to stay logged into Qzone after you enter your username and password. It's typically a set of cookies, with the most important one being qz_screen_key. This token is short-lived and is used for making regular API calls.

  2. Access Token (OAuth2 Token): This is a more modern, standardized token (like those used by WeChat or Facebook). It's obtained through the OAuth2 authorization flow. It's longer-lived and is used for granting third-party applications limited access to a user's Qzone data. This is the preferred method for building legitimate applications.

    Python如何获取QzoneToken?-图2
    (图片来源网络,侵删)

The method you choose depends on your goal. Automating your own account is often done with the login token, while building an app for other users must use the OAuth2 flow.


Method 1: Getting a Login Token (For Automating Your Own Account)

This method simulates a user logging in by providing QQ credentials. It's relatively simple but has major drawbacks:

  • Security Risk: You have to hardcode or input your username and password.
  • Fragile: Tencent frequently changes its login page structure and encryption methods, so this code can break at any time.
  • Risk of Account Lockout: Unusual login behavior can trigger security checks, potentially locking your account.

We will use the popular requests library to handle the HTTP requests.

Step 1: Install the requests library

pip install requests

Step 2: The Python Code

This code performs a simplified version of the login process. The real Qzone login is much more complex, involving multiple redirects, JavaScript challenges, and device fingerprinting. This example captures the core idea but may not work without updates.

import requests
import re
import json
# --- Configuration ---
# WARNING: Using your real credentials in a script is risky.
# Use a dedicated, low-risk QQ account for testing purposes.
QQ_NUMBER = "YOUR_QQ_NUMBER"
QQ_PASSWORD = "YOUR_QQ_PASSWORD"
# --- Main Logic ---
def get_qz_screen_key():
    """
    Attempts to log in to Qzone and retrieve the qz_screen_key cookie.
    NOTE: This is a simplified example and will likely fail due to Tencent's
    complex anti-bot measures. It's for educational purposes only.
    """
    session = requests.Session()
    session.headers.update({
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/108.0.0.0 Safari/537.36'
    })
    # 1. Get the login page to obtain necessary cookies and tokens
    login_url = "https://qzone.qq.com/"
    response = session.get(login_url)
    # The real login URL is embedded in the page content
    # This is a simplified extraction and might not be accurate
    login_form_url_match = re.search(r'login\.qq\.com/ptqrlogin\?u1=', response.text)
    if not login_form_url_match:
        print("Could not find the login form URL. The page structure may have changed.")
        return None
    # 2. Post credentials to the login endpoint
    # This is a highly simplified version. The actual process involves:
    # - Handling QR codes
    # - Answering security questions
    # - Handling JavaScript encryption of the password
    # - Dealing with CAPTCHAs
    login_action_url = "https://ssl.ptlogin2.qq.com/login"
    payload = {
        'u': QQ_NUMBER,
        'p': QQ_PASSWORD, # In a real scenario, this would be an encrypted hash
        'ptredirect': '0',
        'h': '1',
        't': '1',
        'g': '1',
        'from_ui': '1',
        'ptlang': '2052',
        ' Action': 'login',
    }
    # The login page contains a 'verifycode' token that must be included
    verify_code_match = re.search(r'input name="verifycode" type="hidden" value="(.*?)"', response.text)
    if verify_code_match:
        payload['verifycode'] = verify_code_match.group(1)
    print("Attempting to log in...")
    login_response = session.post(login_action_url, data=payload)
    # 3. Check for login success
    # A successful login usually redirects or contains a specific success message
    if "登录成功" in login_response.text or "ptuiCB" in login_response.text:
        print("Login successful!")
        # 4. Access Qzone to get the final cookies
        qzone_main_url = "https://user.qzone.qq.com/" + QQ_NUMBER + "/infocenter"
        session.get(qzone_main_url) # This final request sets the Qzone-specific cookies
        # The qz_screen_key is the most important token for Qzone APIs
        qz_screen_key = session.cookies.get_dict().get('qz_screen_key')
        if qz_screen_key:
            print(f"Successfully obtained qz_screen_key: {qz_screen_key[:20]}...")
            return qz_screen_key
        else:
            print("Login may have succeeded, but could not find qz_screen_key cookie.")
            return None
    else:
        print("Login failed. Response:")
        print(login_response.text)
        return None
# --- Run the function ---
if __name__ == "__main__":
    token = get_qz_screen_key()
    if token:
        # You can now use this token in the 'pt2gguin' parameter for Qzone API calls
        # Example: api_url = "https://mobile.qzone.qq.com/proxy/domain/taotao.qzone.qq.com/cgi-bin/emotion/cgi_bbs_get_all_info_v2.cgi?g_tk={token}&..."
        pass

Why this code is likely to fail: Modern web login forms don't send passwords in plain text. They use JavaScript running in your browser to create a complex hash of your password, a timestamp, and other values. This script doesn't have a browser engine to run that JavaScript, so Tencent's servers will reject the login attempt.


Method 2: Getting an OAuth2 Access Token (The Recommended Way)

This is the official, secure, and robust way to get a token. You don't handle the user's password directly. Instead, you redirect the user to a Tencent login page, they log in and approve your application, and then Tencent redirects them back to your site with an authorization code, which you exchange for an access token.

Prerequisites:

  1. Register a QQ Open Platform Application:
    • Go to the QQ Open Platform.
    • Log in with your QQ account.
    • Create a new application (e.g., a "Website" or "Mobile" application).
    • Fill in the application details. You will need to provide a callback URL (e.g., http://localhost:8000/auth/callback).
    • After creating the app, go to the "Management Center" -> "API Authorization" -> "Modify".
    • Enable the "Qzone API" and note the AppID and AppKey.

Step 1: Install Flask for a simple web server

We need a web server to receive the callback from Tencent.

pip install Flask

Step 2: The Python Code

This code creates a local web server with two routes:

  • A link to start the OAuth2 flow.
  • /auth/callback: The URL that QQ will redirect to after the user logs in.
from flask import Flask, request, redirect, jsonify
import requests
import os
# --- Configuration ---
# Get these from your QQ Open Platform application
APP_ID = 'YOUR_APP_ID'
APP_KEY = 'YOUR_APP_KEY'
# This MUST match the callback URL you configured in your app settings
CALLBACK_URL = 'http://localhost:8000/auth/callback'
# For security, store these as environment variables in a real app
# os.environ['APP_ID'] = 'YOUR_APP_ID'
# os.environ['APP_KEY'] = 'YOUR_APP_KEY'
app = Flask(__name__)
# Step 1: Redirect the user to the QQ authorization page
@app.route('/')
def index():
    auth_url = (
        "https://graph.qq.com/oauth2.0/authorize?"
        "response_type=code&"
        f"client_id={APP_ID}&"
        f"redirect_uri={CALLBACK_URL}&"
        "scope=get_user_info,add_topic" # Request the necessary permissions
    )
    return f'<a href="{auth_url}">Login with QQ to authorize this app</a>'
# Step 2: Handle the callback from QQ
@app.route('/auth/callback')
def auth_callback():
    # The authorization code is sent as a query parameter
    code = request.args.get('code')
    if not code:
        return "Authorization failed. No code was returned.", 400
    # Step 3: Exchange the authorization code for an access token
    token_url = "https://graph.qq.com/oauth2.0/token"
    token_params = {
        'grant_type': 'authorization_code',
        'client_id': APP_ID,
        'client_secret': APP_KEY,
        'code': code,
        'redirect_uri': CALLBACK_URL
    }
    token_response = requests.get(token_url, params=token_params)
    # The response is in the format "access_token=YOUR_TOKEN&expires_in=7776000"
    if token_response.ok:
        token_data = dict(pair.split('=') for pair in token_response.text.split('&'))
        access_token = token_data.get('access_token')
        if access_token:
            # Step 4: Use the access token to get user info (optional, but demonstrates its use)
            user_info_url = "https://graph.qq.com/user/get_user_info"
            user_info_params = {
                'access_token': access_token,
                'oauth_consumer_key': APP_ID, # This is your AppID
                'format': 'json'
            }
            user_info_response = requests.get(user_info_url, params=user_info_params)
            if user_info_response.ok:
                user_info = user_info_response.json()
                return jsonify({
                    "status": "success",
                    "access_token": access_token,
                    "user_info": user_info
                })
            else:
                return f"Failed to get user info: {user_info_response.text}", 500
        else:
            return f"Failed to get access token. Response: {token_response.text}", 500
    else:
        return f"Token exchange failed. Response: {token_response.text}", 500
if __name__ == '__main__':
    # Use reloader to automatically restart the server when code changes
    app.run(port=8000, debug=True)

How to Run This Example:

  1. Save the code as qq_auth.py.
  2. Replace YOUR_APP_ID and YOUR_APP_KEY with your actual credentials.
  3. Make sure your callback URL in the QQ Open Platform is set to http://localhost:8000/auth/callback.
  4. Run the server: python qq_auth.py.
  5. Open your browser and go to http://localhost:8000.
  6. Click the login link. You will be redirected to the official QQ login page.
  7. Log in and approve the permissions for your app.
  8. You will be redirected back to your local server, which will display the JSON response containing the access_token and user information.

Summary and Recommendation

Feature Method 1 (Login Token) Method 2 (OAuth2 Token)
Use Case Automating your own account. Building an app for other users.
Security Low. Requires handling user's password. High. Password never leaves QQ's servers.
Reliability Low. Breaks often with Tencent updates. High. Uses a standardized, stable API.
Complexity Simple to code, but hard to make it work. More setup, but the logic is well-defined.
Best For Personal scripts, learning. Any real-world application.

For any serious project, always use Method 2 (OAuth2). It is the industry standard and is what Tencent officially supports. Method 1 is largely a relic of a past era of web scraping and should be avoided for anything other than personal experimentation.

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