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

Python requests处理同名JSESSIONID cookie丢失问题如何解决

解决requests无法获取同名JSESSIONID的问题

服务端下发两个同名JSESSIONID时,二者的域名或路径属性存在差异,requests默认的CookieJar打印逻辑可能仅展示其中一个,甚至在默认处理逻辑中会遗漏作用域不同的同名Cookie,最稳妥的解决方案是直接读取原始响应头的Set-Cookie字段获取全量Cookie。

方案1:直接读取原始Set-Cookie头确认全量Cookie

import requests

first_url = "https://www.bsesdelhi.com/web/bypl/login"
response = requests.get(first_url)

# 获取所有Set-Cookie原始内容,多组Cookie会以列表形式返回
all_set_cookies = response.headers.getlist("Set-Cookie")
for cookie_str in all_set_cookies:
    print(cookie_str)

运行后即可看到服务端下发的所有Cookie,包含两个JSESSIONID的完整属性(域名、路径、值等)。

方案2:将全量Cookie手动写入会话供后续请求使用

import requests
from http.cookies import SimpleCookie

session = requests.Session()
first_url = "https://www.bsesdelhi.com/web/bypl/login"
response = session.get(first_url)

# 解析所有原始Set-Cookie
cookie = SimpleCookie()
for set_cookie in response.headers.getlist("Set-Cookie"):
    cookie.load(set_cookie)

# 遍历所有解析后的Cookie,手动写入会话的CookieJar
for key, morsel in cookie.items():
    session.cookies.set(
        name=key,
        value=morsel.value,
        domain=morsel["domain"],
        path=morsel["path"],
        secure=morsel["secure"],
        expires=morsel["expires"]
    )

# 后续使用session发起请求即可自动携带两个JSESSIONID

补充说明:两个同名JSESSIONID通常分别对应顶级域.bsesdelhi.com和二级域www.bsesdelhi.com,作用域不同本就可以共存,手动写入后无需额外处理即可正常使用。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.30 09:36:04