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

如何用Python requests维持网站登录?原有Selenium转cookie方法已失效

解决思路与方案

1. 完善Cookie的完整参数传递

原来的代码仅传递了Cookie的name和value,但现代网站的Cookie通常包含domain、path、secure、HttpOnly、SameSite等关键属性,这些属性缺失会导致Cookie无法被目标网站识别。修改Cookie设置代码:

with requests.Session() as s:
    for cookie in cookies:
        s.cookies.set(
            cookie['name'],
            cookie['value'],
            domain=cookie.get('domain'),
            path=cookie.get('path'),
            secure=cookie.get('secure'),
            httponly=cookie.get('httpOnly'),
            samesite=cookie.get('sameSite')
        )

同时,打开浏览器开发者工具(F12)的Application面板,对比Selenium获取的cookies列表和浏览器实际存储的Cookie,确保没有遗漏关键Session类Cookie(如JSESSIONID、session_id等)。

2. 完全模拟浏览器请求头

仅添加User-Agent不足以绕过检测,需要复制浏览器登录后请求的全部请求头到requests Session中:

  • 登录网站后,在F12的Network面板中选取任意一个已登录状态的请求,复制其Request Headers
  • 将这些请求头添加到Session:
with requests.Session() as s:
    # 先执行Cookie设置代码
    # ...
    # 添加完整请求头
    s.headers.update({
        'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,*/*;q=0.8',
        'Accept-Language': 'zh-CN,zh;q=0.8,en-US;q=0.5,en;q=0.3',
        'Accept-Encoding': 'gzip, deflate, br',
        'Referer': 'https://tennis.paris.fr/tennis/jsp/site/Portal.jsp?page=recherche&view=recherche_creneau#',
        'Connection': 'keep-alive',
        'Upgrade-Insecure-Requests': '1',
        # 替换为你浏览器的实际User-Agent
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:109.0) Gecko/20100101 Firefox/115.0'
    })

3. 绕过Selenium指纹检测

目标网站可能更新了反爬机制,识别出请求来自自动化工具,可通过以下方式隐藏Selenium特征:

方法1:修改ChromeOptions

from selenium.webdriver.chrome.options import Options

options = Options()
# 隐藏webdriver标识
options.add_argument('--disable-blink-features=AutomationControlled')
# 禁用扩展
options.add_argument('--disable-extensions')
# 模拟正常窗口大小
options.add_argument('--start-maximized')

driver = webdriver.Chrome(service=Service(ChromeDriverManager().install()), options=options)

方法2:使用undetected-chromedriver库

该库专门针对反爬优化,自动隐藏Selenium指纹:

import undetected_chromedriver as uc

driver = uc.Chrome()

4. 验证请求域名与Cookie的匹配性

检查Cookie的domain属性是否与请求域名一致(比如Cookie的domain是.paris.fr,则请求tennis.paris.fr时会自动携带;如果domain是tennis.paris.fr,则不能省略前缀)。同时确保请求的URL路径与Cookie的path属性匹配。

5. 备选方案:直接用Selenium完成爬取

如果上述方法都无法解决Cookie传递问题,可放弃requests,直接使用Selenium完成后续的页面请求和数据提取,这样能完全保持登录状态的一致性,避免Cookie传递的兼容性问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.18 18:51:03