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

Selenium如何获取domain.com域名下的LocalStorage数据?

解决方法

要获取domain.com域名下的localStorage,核心是绕开同源限制——既然website.com能设置该域名的存储,说明两者大概率属于同一主域(或存在合法的跨域通信机制),直接用以下两种方式即可:

方法一:切换到domain.com的iframe上下文读取

如果页面本身没有嵌入domain.com的iframe,可以动态创建一个,然后切换到iframe的执行上下文直接读取:

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

# 打开目标页面
driver.get("website.com")

# 动态创建并插入指向domain.com的iframe
driver.execute_script("""
const iframe = document.createElement('iframe');
iframe.src = 'https://domain.com';
iframe.id = 'domain_iframe';
iframe.style.display = 'none';
document.body.appendChild(iframe);
""")

# 等待iframe加载完成并切换到该iframe
WebDriverWait(driver, 10).until(EC.frame_to_be_available_and_switch_to_it((By.ID, "domain_iframe")))

# 直接读取domain.com的localStorage中specialinfo的值
special_info = driver.execute_script("return window.localStorage.getItem('specialinfo');")

# 切回原页面上下文
driver.switch_to.default_content()

# 输出结果
print(special_info)

方法二:通过postMessage跨域通信读取

如果不想切换iframe上下文,可以利用跨域消息传递,让domain.com的页面主动返回存储值:

# 打开website.com页面
driver.get("website.com")

# 执行JS代码,通过postMessage获取值
special_info = driver.execute_script("""
return new Promise(resolve => {
    // 创建隐藏iframe
    const iframe = document.createElement('iframe');
    iframe.src = 'https://domain.com';
    iframe.style.display = 'none';
    document.body.appendChild(iframe);

    // 监听返回消息
    const messageHandler = event => {
        if (event.origin === 'https://domain.com' && event.data.action === 'returnSpecialInfo') {
            window.removeEventListener('message', messageHandler);
            document.body.removeChild(iframe);
            resolve(event.data.value);
        }
    };
    window.addEventListener('message', messageHandler);

    // iframe加载后发送读取请求
    iframe.onload = () => {
        iframe.contentWindow.postMessage({action: 'getSpecialInfo'}, 'https://domain.com');
    };
});
""")

print(special_info)

需要注意:第二种方法需要domain.com的页面配合监听message事件并返回数据,如果网站本身已经有设置该存储的逻辑,大概率已经存在对应的通信处理,直接用即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.21 08:36:22