You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何修复urllib.error.HTTPError: HTTP Error 403: Forbidden报错

Fixing urllib.error.HTTPError: 403 Forbidden for nekos.life API

Let's work through this 403 error and get your code working properly:

Why you're seeing this 403

Most websites and APIs block requests that don't include a proper User-Agent header. The default User-Agent used by urllib.request.urlopen looks like Python-urllib/3.x, which servers often flag as suspicious (non-browser/crawler traffic) and reject with a 403 Forbidden response.

Also, your current code uses regex to pull links from the API response—but the nekos.life API returns valid JSON, so regex is unnecessary and error-prone. We'll fix that too.

Step-by-step solution

Here's the revised code that addresses both issues:

import re
import json
from urllib.request import urlopen, Request
from urllib.error import HTTPError, URLError

@client.event
async def on_message(message):
    if message.content.startswith(prefix + 'getimg'):
        # Mimic a browser request with custom headers
        headers = {
            'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/114.0.0.0 Safari/537.36'
        }
        
        try:
            # Build the request with headers included
            req = Request('https://nekos.life/api/hug', headers=headers)
            website = urlopen(req)
            
            # Parse the JSON response directly (no regex needed!)
            response_data = json.load(website)
            image_url = response_data['url']  # The API returns the image link under the 'url' key
            
            print(f"Fetched image URL: {image_url}")
            await client.send_message(message.channel, image_url)  # Send the actual image link instead of 'get'
        
        except HTTPError as e:
            print(f"HTTP Error: {e.code} - {e.reason}")
            await client.send_message(message.channel, f"Failed to get image: {e.reason}")
        except URLError as e:
            print(f"Network Error: {e.reason}")
            await client.send_message(message.channel, f"Network issue: {e.reason}")
        except KeyError:
            print("API response format changed—couldn't find 'url' key")
            await client.send_message(message.channel, "Failed to parse image link from API")

What changed and why:

  • Custom headers: The User-Agent makes your request look like it's coming from a regular Chrome browser, which most servers will accept.
  • JSON parsing: Instead of regex, we directly load the API's JSON response and extract the url field—this is way more reliable than string matching.
  • Error handling: We catch common failures (HTTP errors, network issues, unexpected API responses) so your bot can handle problems gracefully instead of crashing.

Quick tips

  • You can use other common browser User-Agent strings if needed, but the one provided works for most cases.
  • Always check API docs first (when available) to see if they require specific headers or auth—nekos.life doesn't need a key, but some APIs do.

内容的提问来源于stack exchange,提问作者Юмейнару Фрейм

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 06:40:00