python network_error ai_generated true

aiohttp.client_exceptions.InvalidURL: URL 应为绝对地址

aiohttp.client_exceptions.InvalidURL: URL should be absolute

ID: python/aiohttp-invalid-url-with-scheme

其他格式: JSON · Markdown 中文 · English
80%修复率
88%置信度
0证据数
2024-04-11首次发现

版本兼容性

版本状态引入弃用备注
3.8 active — — —
3.9 active — — —
3.10 active — — —
3.11 active — — —

根因分析

aiohttp 要求完全限定的 URL,必须包含协议和主机;相对路径或缺少 http(s):// 的字符串会被拒绝。

English

aiohttp requires fully qualified URLs including scheme and host; relative paths or strings missing http(s):// are rejected.

generic

解决方案

  1. 95% 成功率
    Use urllib.parse.urljoin to build an absolute URL:
    
    from urllib.parse import urljoin
    url = urljoin('https://api.example.com', '/v1/users')
    async with session.get(url) as resp:
        ...
  2. 90% 成功率
    Store full URLs in your config and validate at startup:
    
    assert url.startswith(('http://', 'https://')), f'bad url: {url}'

无效尝试

常见但无效的做法:

  1. 70% 失败

    base_url only affects redirects and links; session.get('/path') still raises InvalidURL.

  2. 80% 失败

    Encoding does not add the missing scheme/host; the URL remains relative.