使用 VBA 和 Selenium 访问网站的本地存储键/值项返回空值



我手动打开Chrome浏览器并转到'https://www.google.com/',然后按F12转到开发人员工具。然后我转到控制台并键入localStorage.key(0)以获得本地存储中第一个项目的密钥,然后我得到">whatever"。

但是,当我运行以下测试代码时,firstKey中的返回值为Empty。

Sub GetLocalStorage()
Dim driverGoogle As Object
Dim firstKey As Variant

Set driverGoogle = CreateObject("Selenium.Chromedriver")

driverGoogle.Get "https://www.google.com/"
driverGoogle.Window.SetSize 1800, 1050

firstKey = driverGoogle.ExecuteScript("localStorage.key(0);")
End Sub

我甚至将localStorage.key(0)更改为不正确的localStorage.aaakey(0),以确保ExecuteScript确实在执行,并且Selenium确实抛出了一个错误。

那么,如何获取本地存储密钥/值呢?

您必须添加延迟才能加载站点
当前,您正在尝试在页面刚开始加载时,在将URL发送到web驱动程序后立即应用driverGoogle.ExecuteScript("localStorage.key(0);")脚本。

ExecuteScript字符串需要"return"指令。添加后一切正常。

firstKey = driverGoogle.ExecuteScript("return localStorage.key(0);")

最新更新