我目前在代码的这一部分遇到了问题:
webDriver.manage().window().setSize(new Dimension(width,height));
TimeUnit.MILLISECONDS.sleep(100);
webDriver.executeScript("window.scrollTo(0,document.body.scrollHeight);");
问题是我希望我的屏幕在脚本执行之前调整大小并执行滚动,而sleep命令可以帮助我实现这一点。但是如果我删除它,滚动有时会在屏幕调整大小之前发生。我试过用ExpectedCondition检查替换睡眠:
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);");
我认为这会奏效,但问题仍然存在。有人有什么想法吗?
编辑:忘记提及我要删除睡眠并用逻辑方式替换它以检查屏幕是否已调整大小。
答案 0 :(得分:0)
我认为你指定的时间是太低了。
WebDriverWait wait = new WebDriverWait(webDriver, 1);
保持如下:
WebDriverWait wait = new WebDriverWait(webDriver, 10);
这允许方法wait Up to 10 seconds
在抛出异常之前检查条件。
来自Selenium Docs:
WebDriver driver = new FirefoxDriver();
driver.get("http://somedomain/url_that_delays_loading");
WebElement myDynamicElement = (new WebDriverWait(driver, 10))
.until(ExpectedConditions.presenceOfElementLocated(By.id("myDynamicElement")));
在抛出TimeoutException之前等待最多10秒或者等待 它发现元素将在0-10秒内返回。 WebDriverWait 默认情况下,每500毫秒调用一次ExpectedCondition直到它 成功返回。成功的返回值 ExpectedCondition函数类型是布尔值true或a 非空对象。
参考文献:
答案 1 :(得分:0)
如果在调整窗口大小时文档大小发生变化,您可以尝试等待<defns:Code typeCode="Name">
John
</defns:Code>
<defns:Code1 typeCode="ID">
12345
</defns:Code1>
<defns:Code2 typeCode="address">
Addresss 1234
</defns:Code2>
<defns:Text typeCode="Name">
Doe
</defns:Text>
<defns:Text2 typeCode="ID">
123
</defns:Text2>
<defns:Text3 typeCode="Address">
Address 4567
</defns:Text3>
更改:
<defns:Code typeCode="Name">
John
</defns:Code>
<defns:Code typeCode="ID">
12345
</defns:Code>
<defns:Code typeCode="address">
Addresss 1234
</defns:Code>
<defns:Text typeCode="Name">
Doe
</defns:Text>
<defns:Text typeCode="ID">
123
</defns:Text>
<defns:Text typeCode="Address">
Address 4567
</defns:Text>
如果没有,您还可以尝试等待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);