简体   繁体   English

Selenium webDriver - 等待 cookies 和 java 中的本地数据库 cookies

[英]Selenium webDriver - wait for cookies and local db cookies in java

I use selenium to get cookies and local db cookies in java.我使用 selenium 在 java 中获取 cookies 和本地数据库 cookies。

if I use following code to wait the side will be ready I don't get all the cookies:如果我使用以下代码等待端准备就绪,我不会得到所有 cookies:

webDriverWait.until(webDriver -> "complete".equals((JavascriptExecutor) webDriver.executeScript("return document.readyState")))

I saw that if I wait enough of time eventually I will get all the cookies (regular cookies and userData cookies that saved in local db).我看到,如果我等待足够长的时间,最终我将获得所有 cookies(保存在本地数据库中的常规 cookies 和 userData cookies)。

Is there a way to use webDriverWait to wait until all the cookies will be load?有没有办法使用 webDriverWait 等待所有 cookies 加载?

You never know if your client loaded all the possible cookies. Because if you have asynchronous UI each new request might add new cookie or modify existing one.你永远不知道你的客户端是否加载了所有可能的 cookies。因为如果你有异步 UI,每个新请求都可能添加新的 cookie 或修改现有的 cookie。

So the better, more reliable and "proper" approach would be to first of all know which cookies exactly you expect to have.因此,更好、更可靠和“正确”的方法是首先知道您希望拥有哪个 cookies。 Say you keep the names in Set<String> cookieNames .假设您将名称保存在Set<String> cookieNames中。

Then your wait would look like:然后你的等待看起来像:

webDriverWait.until(
        webDriver -> {
            Set<Cookie> cookies = webDriver.manage().getCookies();
            return cookies.size() == cookieNames.size() &&
                    cookies.stream().allMatch(cookie -> cookieNames.contains(cookie.getName()));
        }
);

or if your frontend is using Angular, you can wait until this script is true (meaning the site is fully loaded) and then can continue with your script for fetching cookies:或者,如果您的前端正在使用 Angular,您可以等到此脚本为真(意味着站点已完全加载),然后可以继续使用您的脚本来获取 cookies:

return window.getAllAngularTestabilities().findIndex(x => !x.isStable()) === -1

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM