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

使用Selenium登录后用Python Requests请求返回401错误求助

Selenium登录后传递Cookie到Requests仍返回401的解决办法

你的问题核心是Selenium同步给Requests的Cookie未被目标网站正确识别,导致权限验证失败(401)。以下是针对性的修复方案:

1. 完整同步Cookie的所有属性

直接用session.cookies.set(name, value)会丢失Cookie的domain、path等关键属性,这些属性决定了Cookie是否能匹配目标请求的域名路径。修改Cookie同步代码:

for cookie in webdriver.get_cookies():
    session.cookies.set(
        cookie['name'],
        cookie['value'],
        domain=cookie.get('domain'),
        path=cookie.get('path'),
        secure=cookie.get('secure'),
        expires=cookie.get('expires')
    )

2. 补充动态生成的请求头令牌

很多网站会验证x-csrf-token或类似动态令牌,这类令牌不会存于Cookie中,需从登录后的页面提取:

# 登录成功后,从页面提取CSRF令牌(根据实际页面元素定位调整)
csrf_token = WebDriverWait(webdriver, 10).until(
    EC.presence_of_element_located((By.CSS_SELECTOR, 'meta[name="csrf-token"]'))
).get_attribute('content')
# 将令牌加入请求头
headers['x-csrf-token'] = csrf_token

3. 调整浏览器关闭时机

部分网站会在浏览器进程关闭时主动失效会话,建议先发送Requests请求,再关闭浏览器:

# 先执行请求
response = session.request("GET", url, headers=headers)
print(response.text)
# 再关闭浏览器
webdriver.close()

4. 验证Cookie同步完整性

同步Cookie后,打印session.cookies,对比浏览器F12→Application→Cookies中的内容,确认sessionid、auth_token这类核心会话Cookie是否已正确同步。

修改后的完整代码示例

import selenium
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By
from selenium.webdriver.support.wait import WebDriverWait
import requests

webdriver = selenium.webdriver.Firefox()
session = requests.Session()

webdriver.get("example.website")

# 登录流程
email_field = WebDriverWait(webdriver, 10).until(EC.element_to_be_clickable((By.ID, "username-field")))
email_field.send_keys("username")
password_field = WebDriverWait(webdriver, 10).until(EC.element_to_be_clickable((By.ID, "password-field")))
password_field.send_keys("password")
WebDriverWait(webdriver, 10).until(EC.element_to_be_clickable((By.CSS_SELECTOR, "login-button"))).click()

# 等待登录完成
WebDriverWait(webdriver, 10).until(EC.url_matches("loggedin.url"))

# 完整同步Cookie属性
for cookie in webdriver.get_cookies():
    session.cookies.set(
        cookie['name'],
        cookie['value'],
        domain=cookie.get('domain'),
        path=cookie.get('path'),
        secure=cookie.get('secure'),
        expires=cookie.get('expires')
    )

# 提取CSRF令牌(根据实际页面调整)
csrf_token = WebDriverWait(webdriver, 10).until(
    EC.presence_of_element_located((By.CSS_SELECTOR, 'meta[name="csrf-token"]'))
).get_attribute('content')

url = "url.for/request"

headers = {
    "authority": "authority.url",
    "accept": "application/json, text/plain, */*",
    "accept-language": "en-US,en;q=0.9,de-DE;q=0.8,de;q=0.7,en-GB;q=0.6",
    "content-type": "application/json",
    "referer": "referal.url",
    "sec-ch-ua-mobile": "?0",
    "sec-ch-ua-platform": "Linux",
    "sec-fetch-dest": "empty",
    "sec-fetch-mode": "cors",
    "sec-fetch-site": "same-origin",
    "user-agent": "Mozilla/5.0 (X11; Linux x86_64; rv:104.0) Gecko/20100101 Firefox/104.0",
    "x-csrf-token": csrf_token  # 添加CSRF令牌
}

# 发送请求后再关闭浏览器
response = session.request("GET", url, headers=headers)
print(response.text)

webdriver.close()

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.18 00:55:54