英文:
How to load a "local storage" value to HtmlUnit web client?
问题
我尝试在HtmlUnit Web客户端加载特定网站之前将本地存储值加载到其中:
HtmlPage initialPage = webClient.getPage(url);
if (httpHeadersSpec != null && httpHeadersSpec.getLocal_storage() != null) {
for (StorageItemSpec item : httpHeadersSpec.getLocal_storage()) {
initialPage.executeJavaScript(
"localStorage.setItem('" + item.getKey() + "', '" + item.getValue() + "');");
}
}
HtmlPage page = webClient.getPage(url);
webClient.waitForBackgroundJavaScriptStartingBefore(3000);
URL baseUrl = page.getFullyQualifiedUrl(page.getBaseURI());
问题是:
- 我如何检查本地存储值是否已加载?
- 在加载页面之前,将浏览器的本地存储值加载到HtmlUnit的正确方法是什么?
英文:
I'm trying to load a local storage value into the HtmlUnit web client before it loads a specific website:
HtmlPage initialPage = webClient.getPage(url);
if (httpHeadersSpec != null && httpHeadersSpec.getLocal_storage() != null) {
for (StorageItemSpec item : httpHeadersSpec.getLocal_storage()) {
initialPage.executeJavaScript(
"localStorage.setItem('" + item.getKey() + "', '" + item.getValue() + "');");
}
}
HtmlPage page = webClient.getPage(url);
webClient.waitForBackgroundJavaScriptStartingBefore(3000);
URL baseUrl = page.getFullyQualifiedUrl(page.getBaseURI());
The problems are:
- How do I check if the local storage value is loaded?
- What is the correct approach to load a browser's local storage value to HtmlUnit before loading a page?
答案1
得分: 1
迄今为止(HtmlUnit 3.3.0版本)还没有真正的公共API可以在js支持之外与存储进行交互。
请在GitHub上提交一个问题,我们可以一起工作,添加一些方法来支持您的情况(也许还有一些文档)。
英文:
So far (HtmlUnit 3.3.0) there is no real public API to do interaction with the storage outside of the js support.
Please open an issue at github and we can work together to add some methods to support your case (and maybe some documentation also).
答案2
得分: 1
从版本3.4.0开始,有一种已记录的方法来执行此操作(https://www.htmlunit.org/details.html#Local.2FSession_Storage)。
try (WebClient webClient = new WebClient()) {
// 获取URL的本地存储
// URL必须与稍后加载的页面URL匹配
final Map<String, String> localStorage = webClient.getStorageHolder().getLocalStorage(url);
// 将一些数据放入会话存储
localStorage.put("myKey", "myData");
// 加载使用会话存储数据的页面
webClient.getPage(url);
// 确保新数据已经存在
assertEquals("myNewData", localStorage.get("myNewKey"));
}
(顺便说一下,最新的3.4.0-SNAPSHOT版本已经包含了这个功能)
英文:
Starting with version 3.4.0 there is a documented (https://www.htmlunit.org/details.html#Local.2FSession_Storage) way to do this.
try (WebClient webClient = new WebClient()) {
// get the local storage for the url
// the url has to match the page url you will load later
final Map<String, String> localStorage = webClient.getStorageHolder().getLocalStorage(url);
// place some data in the session storage
localStorage.put("myKey", "myData");
// load the page that consumes the session storage data
webClient.getPage(url);
// make sure the new data are in
assertEquals("myNewData", localStorage.get("myNewKey"));
}
(Btw the latest 3.4.0-SNAPSHOT already constains this)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论