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

aiohttp请求返回403 Forbidden,requests.get返回200的问题求助

问题分析与解决方案

403 Forbidden错误的核心原因是服务器识别到aiohttp的请求与requests的请求存在差异,大概率是请求头(如User-Agent)不符合服务器的反爬校验规则——requests默认会携带类似浏览器的User-Agent,而aiohttp的默认User-Agent是Python/3.x aiohttp/3.x.x,很容易被服务器拦截。你尝试的URL规范化并不是问题的根源。

解决步骤

  1. 对齐请求头
    服务器通常会通过请求头判断请求是否来自合法客户端,将requests使用的请求头复制到aiohttp中,模拟真实浏览器的请求特征。

  2. 修改代码添加请求头
    在aiohttp的请求中加入headers参数,至少携带User-Agent,建议补充Accept、Accept-Language等常见浏览器头。

修改后的代码

import requests
import asyncio
from aiohttp import ClientSession

url = 'https://www.yescapa.fr/s?seatbelts=4&beds=4&km_unlimited=true&less_than_five=true&cooking=true&sink=true&fridge=true&wc=true&heating=true&types=4&longitude=-0.58046&latitude=44.84135&radius=50000&date_from=2024-08-01&date_to=2024-08-29&page=1'

# 查看requests的请求头作为参考
res = requests.get(url)
print("requests状态码:", res.status_code)

async def test(url):
    # 模拟浏览器请求头,可根据实际场景调整补充
    headers = {
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/126.0.0.0 Safari/537.36',
        'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8',
        'Accept-Language': 'en-US,en;q=0.5',
        'Connection': 'keep-alive',
        'Upgrade-Insecure-Requests': '1'
    }
    async with ClientSession() as session:
        async with session.get(url, headers=headers) as response:
            return response.status

print("aiohttp状态码:", asyncio.run(test(url)))

额外注意事项

  • 如果添加上述头后仍返回403,可以尝试直接复制res.request.headers中的所有字段(包括Cookie,若服务器依赖会话验证)到aiohttp的headers中。
  • 避免短时间内频繁发起请求,必要时在异步任务中加入await asyncio.sleep(1)这类延迟,防止触发频率限制。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.21 04:35:10