You need to enable JavaScript to run this app.
最新活动
大模型
产品
解决方案
定价
生态与合作
支持与服务
开发者
了解我们

Python Requests请求404 Not Found问题及登录接口报错解决方案咨询

Troubleshooting 404 Not Found When Logging in via Python Requests

Let’s break down why you’re hitting that 404 error and fix it step by step:

Key Issues in Your Current Code

  • Incorrect parameter separators: Your PostData() returns a string with & (HTML-escaped ampersands) instead of plain &. This will cause the server to misparse your request parameters, leading to invalid endpoint handling.
  • Manual Content-Length header: You’re hardcoding this value, but if your post data changes even slightly, this will mismatch the actual payload length. Requests automatically calculates this for you, so removing it avoids this mismatch.
  • Missing pre-flight session setup: Many authentication flows require you to first visit the login page to establish a valid session (including cookies like CSRF tokens) before sending the login POST request.

Fixed Code Implementation

Here’s the revised version that addresses these issues:

import requests

def get_headers():
    headerdata = {
        'Host': 'api.cathaypacific.com',
        'Connection': 'keep-alive',
        'Cache-Control': 'max-age=0',
        'Origin': 'https://www.asiamiles.com',
        'Upgrade-Insecure-Requests': '1',
        'Content-Type': 'application/x-www-form-urlencoded',
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/76.0.3809.132 Safari/537.36',
        'Sec-Fetch-Mode': 'navigate',
        'Sec-Fetch-User': '?1',
        'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3',
        'Sec-Fetch-Site': 'cross-site',
        'Accept-Encoding': 'gzip, deflate, br',
        'Accept-Language': 'ar-EG,ar;q=0.9,en-US;q=0.8,en;q=0.7'
        # Removed manual Content-Length - requests handles this automatically
    }
    return headerdata

def get_post_data():
    # Using a dictionary for cleaner, error-free parameter handling
    data = {
        'response_type': 'code',
        'scope': 'openid offline_access',
        'redirect_uri': 'https://api.asiamiles.com/profile/api/v2/createSessionAndRedirect',
        'client_id': 'de07768c-6e6d-4b48-81f3-dbf50618e598',
        'login_url': 'https://www.asiamiles.com/en/login.html',
        'target_url': 'https://www.asiamiles.com/en/account/account-overview.html',
        'state': '',
        'username': '1707617679',
        'password': '*123qweQWE'
    }
    return data

def establish_login_request():
    # First, establish a session by visiting the login page to get necessary cookies
    session = requests.Session()
    login_page_url = 'https://www.asiamiles.com/en/login.html'
    session.get(login_page_url)  # This sets up initial session cookies

    url = 'https://api.cathaypacific.com/mlc2/authorize'
    response = session.post(url=url, data=get_post_data(), headers=get_headers())
    
    print(f"Status Code: {response.status_code} {response.reason}")
    print(f"Is Redirect: {response.is_redirect}")
    print(f"Request Duration: {response.elapsed}")
    print(f"Redirect Location: {response.headers.get('Location')}")

establish_login_request()

Additional Checks to Try

  • Verify the endpoint URL: Double-check if https://api.cathaypacific.com/mlc2/authorize is still the correct authentication endpoint—APIs sometimes change paths without notice.
  • Check for CSRF tokens: If the login page has a hidden CSRF token in its HTML, you’ll need to extract it (using a library like BeautifulSoup) and include it in your POST data (usually as a _csrf or similar parameter).
  • Inspect browser traffic: Use Chrome DevTools or Firefox Network Monitor to capture the exact request your browser sends when logging in. Compare headers, parameters, and cookies with your requests code to spot missing or mismatched elements.

内容的提问来源于stack exchange,提问作者Hassan Ibraheem

火山引擎 最新活动