gpt4 book ai didi

java - 在使用 Selenium Web 驱动程序执行脚本之前如何等待屏幕大小调整?

转载 作者:行者123 更新时间:2023-12-02 07:34:13 24 4
gpt4 key购买 nike

我目前的这部分代码有问题:

webDriver.manage().window().setSize(new Dimension(width,height));
TimeUnit.MILLISECONDS.sleep(100);
webDriver.executeScript("window.scrollTo(0,document.body.scrollHeight);");

问题是我希望在脚本执行和滚动之前调整屏幕大小,而 sleep 命令可以帮助我实现这一目标。但如果我删除它,滚动有时会在调整屏幕大小之前发生。我尝试用 ExpectedCondition 检查替换 sleep :

private boolean waitForScreenToResize(final int HEIGHT) {
WebDriverWait wait = new WebDriverWait(webDriver, 1);

ExpectedCondition<Boolean> screenResized = new ExpectedCondition<Boolean>() {
@Override
public Boolean apply(WebDriver webDriver) {
return webDriver.manage().window().getSize().getHeight() == HEIGHT;
}
};

return wait.until(screenResized);
}

webDriver.manage().window().setSize(new Dimension(width,height));
waitForScreenToResize(height);
webDriver.executeScript("window.scrollTo(0,document.body.scrollHeight);");

我以为这会起作用,但问题仍然存在。大家有什么想法吗?

编辑:忘记提及我想删除 sleep 并将其替换为检查屏幕大小是否已调整的逻辑方法。

最佳答案

如果调整窗口大小时文档大小发生变化,您可以尝试等待 scrollHeight 发生变化:

String JS_GET_SCROLL_HEIGHT = "return Math.max(document.documentElement.scrollHeight, document.body.scrollHeight) | 0;";
String JS_SCROLL_BOTTOM = "window.scroll(0, -1 >>> 1);";

// get the current scroll height
Object scrollHeight = driver.executeScript(JS_GET_SCROLL_HEIGHT);

// set the size of the window
driver.manage().window().setSize(new Dimension(width, height));

// wait for the scroll height to change
new WebDriverWait(driver, 10)
.until(drv -> !drv.executeScript(JS_GET_SCROLL_HEIGHT).equals(scrollHeight));

// scroll to the bottom
driver.executeScript(JS_SCROLL_BOTTOM);

如果没有,您也可以尝试等待innerHeight改变:

String JS_GET_INNER_HEIGHT = "return window.innerHeight | 0;";
String JS_SCROLL_BOTTOM = "window.scroll(0, -1 >>> 1);";

// get the current scroll height
Object innerHeight = driver.executeScript(JS_GET_INNER_HEIGHT);

// set the size of the window
driver.manage().window().setSize(new Dimension(width, height));

// wait for the scroll height to change
new WebDriverWait(driver, 10)
.until(drv -> !drv.executeScript(JS_GET_INNER_HEIGHT).equals(innerHeight));

// scroll to the bottom
driver.executeScript(JS_SCROLL_BOTTOM);

关于java - 在使用 Selenium Web 驱动程序执行脚本之前如何等待屏幕大小调整?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40236202/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com