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

如何使用Python Selenium获取Bearer Token?

Selenium获取Bearer Token的实现方法

Bearer Token本质是前端登录后存储在客户端、后续发接口请求时放在Authorization头里的认证凭证,Selenium里可以根据token的存储/传输位置,选下面三种常用方案获取:

  • 方案1:从Web存储中直接读取(最简单,优先试)
    绝大多数网站会把登录后的token存在localStorage或者sessionStorage里,你可以先手动打开目标网站F12,在「应用/Application」面板下找到对应存储项,确认存token的键名(常见键名有access_token、token、bearer_token),之后直接用JS执行脚本读取即可:
    from selenium import webdriver
    driver = webdriver.Chrome()
    # 必须先跳转到目标网站对应域名下,否则跨域无法读取存储
    driver.get("https://你的目标站点地址")
    # 读取localStorage中的token
    bearer_token = driver.execute_script("return window.localStorage.getItem('access_token')")
    # 如果token存在sessionStorage中,替换成下面这行
    # bearer_token = driver.execute_script("return window.sessionStorage.getItem('access_token')")
    
  • 方案2:拦截网络请求抓取Authorization头(通用性最强)
    如果前端没有把token存在Web存储里,或者你不想手动找存储键名,可以用Selenium 4+自带的CDP能力监听所有网络请求,直接从请求头里提取Bearer Token,不管token存在哪只要发请求带了就能抓到:
    from selenium import webdriver
    import time
    
    driver = webdriver.Chrome()
    bearer_token = None
    # 开启CDP网络监听
    driver.execute_cdp_cmd("Network.enable", {})
    
    def catch_auth_token(event):
        global bearer_token
        req_headers = event["request"]["headers"]
        auth_value = req_headers.get("Authorization", "")
        if auth_value.startswith("Bearer "):
            bearer_token = auth_value.split(" ")[1]
    
    # 绑定请求监听回调
    driver.execute_cdp_cmd(
        "Network.requestWillBeSent",
        {"callback": catch_auth_token}
    )
    
    # 执行正常的页面访问、登录操作,触发带认证信息的接口请求
    driver.get("https://你的目标站点地址")
    # 等待接口请求完成,生产环境建议换成显式等待判断token非空,不要硬等
    time.sleep(3)
    print("抓取到的Bearer Token:", bearer_token)
    
  • 方案3:从Cookie中提取
    少数站点会把Bearer Token存在Cookie的指定字段里,这种情况直接调用Selenium的Cookie读取接口即可:
    # 提前确认存token的Cookie键名,比如键名为auth_token
    token_cookie = driver.get_cookie("auth_token")
    if token_cookie:
        bearer_token = token_cookie["value"]
    

补充说明:Insomnia这类API客户端导入cURL后能自动识别Bearer Token,本质是直接解析了你复制的cURL文本里自带的Authorization请求头或者认证Cookie,并非客户端主动发起请求获取的。

内容的提问来源于stack exchange,提问作者Shing Yan Yuen

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.28 03:20:02