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

使用Python获取浏览器localStorage存储项,是否有比selenium更简便的实现方式?

Python读取浏览器localStorage的轻量实现方案

不存在和localStorage.getItem("name")完全等效的单步Python接口,因为浏览器的localStorage属于浏览器沙箱隔离的存储资源,不同浏览器、不同用户配置的存储路径、加密规则、存储格式都不统一,且默认禁止外部进程直接访问运行中浏览器的存储数据。但确实存在远比重度依赖浏览器驱动的Selenium更轻量的实现方案,可根据你的使用场景选择:

方案1:直接读取浏览器本地存储文件(适合离线读取)

Chromium内核浏览器(Chrome、Edge、Brave等)

Chromium的localStorage基于LevelDB存储,对应的文件路径为:

  • Windows:C:\Users\<你的系统用户名>\AppData\Local\Google\Chrome\User Data\Default\Local Storage\leveldb
  • macOS:~/Library/Application Support/Google/Chrome/Default/Local Storage/leveldb
  • Linux:~/.config/google-chrome/Default/Local Storage/leveldb

先安装依赖:pip install plyvel
示例代码:

import plyvel

# 替换为你的浏览器对应的leveldb存储路径
db_path = r"C:\Users\test\AppData\Local\Google\Chrome\User Data\Default\Local Storage\leveldb"
# 替换为目标站点的前缀,格式为b'_<协议>://<域名>:<端口>\x00\x01'
site_prefix = b'_http://localhost:3000\x00\x01'
target_key = b'name'

db = plyvel.DB(db_path, compression=None, create_if_missing=False)
for k, v in db:
    if k.startswith(site_prefix) and k.endswith(target_key):
        # localStorage值默认以utf-16le编码存储
        print(v.decode('utf-16le').strip('\x00'))
db.close()

Firefox浏览器

Firefox的localStorage存储在sqlite数据库文件中,路径为:

  • Windows:C:\Users\<你的系统用户名>\AppData\Roaming\Mozilla\Firefox\Profiles\<你的配置文件夹名>\webappsstore.sqlite
  • macOS:~/Library/Application Support/Firefox/Profiles/<你的配置文件夹名>/webappsstore.sqlite
  • Linux:~/.mozilla/firefox/<你的配置文件夹名>/webappsstore.sqlite

无需额外安装依赖,用Python自带的sqlite3即可读取:

import sqlite3

# 替换为你的Firefox对应的sqlite文件路径
db_path = r"C:\Users\test\AppData\Roaming\Mozilla\Firefox\Profiles\abc123.default-release\webappsstore.sqlite"
# 替换为目标站点的域名
target_origin = "http://localhost:3000"
target_key = "name"

conn = sqlite3.connect(db_path)
cursor = conn.cursor()
cursor.execute("SELECT value FROM webappsstore2 WHERE originKey = ? AND key = ?", (target_origin, target_key))
res = cursor.fetchone()
if res:
    print(res[0])
conn.close()

注意:读取本地文件的方案需要先关闭对应浏览器的所有窗口,否则存储文件会被浏览器进程加独占锁无法读取。

方案2:通过浏览器远程调试接口读取(适合读取运行中浏览器的存储)

无需引入Selenium的整套驱动依赖,仅通过浏览器原生的调试接口即可执行JS命令读取localStorage,操作步骤:

  1. 启动浏览器时添加远程调试参数,例如Chrome启动命令添加--remote-debugging-port=9222
  2. 访问http://localhost:9222/json获取目标标签页的webSocketDebuggerUrl
  3. 安装依赖:pip install websocket-client
  4. 示例代码:
import json
import websocket

# 替换为你获取到的webSocketDebuggerUrl
ws_url = "ws://localhost:9222/devtools/page/xxxxxx"
ws = websocket.create_connection(ws_url)

cmd = {
    "id": 1,
    "method": "Runtime.evaluate",
    "params": {"expression": "localStorage.getItem('name')"}
}
ws.send(json.dumps(cmd))
result = json.loads(ws.recv())
print(result['result']['result']['value'])
ws.close()

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.04 19:21:02