我有一个无法继续进行的情况:
我在页面上有两个按钮(两个按钮都在同一帧中)。我正在为 Button 1
使用 Iterator
。当我们单击 Button 1
时,它会进行 AJAX 调用。我看到鼠标加载动画一秒钟,然后产品被添加到购物车。
比如说,如果我有 5 个相同类型的按钮并且想要单击所有 5 个按钮,当我使用迭代器单击 5 个按钮时,控件将退出循环而不是单击第二个按钮。
Iterator<WebElement> button1 = T2.iterator();
while(button1.hasNext()) {
button1.next().click();
Thread.sleep(10000);
}
driver.findElement(By.id("button2 id")).click();
如果我使用 Thread.sleep()
,它工作正常。但我不想使用它,因为它不是正确的方法。
按钮 2 id 也处于启用状态,我无法使用 Wait for the element to be enabled
.当执行到 button1.next().click()
时,我立即转到下一行,而不是完成循环。如果我在 button1.next().click()
之后打印一些文本,文本会打印 5 次。但是不知道为什么按钮没有被点击。
甚至尝试过隐式等待,但没有成功。
避免此类问题的最佳方法是什么?
最佳答案
正确的方法是明确等待产品添加到购物车。操作完成后页面会发生一些变化,对吗?所以等待那个改变发生!显然,我不知道您的网页,但大概是这样的:
// earlier
import static org.openqa.selenium.support.ui.ExpectedConditions.*;
// also earlier, if you want, but you can move it to the loop
WebDriverWait wait = new WebDriverWait(driver, 10);
Iterator<WebElement> button = T2.iterator();
while(button.hasNext()) {
// find the current number of products in the cart
String numberOfProductsInCart = driver.findElement(By.id("cartItems")).getText();
button.next().click();
// wait for the number of items in cart to change
wait.until(not(textToBePresentInElement(By.id("cartItems"), numberOfProductsInCart)));
}
关于java - Selenium Webdriver AJAX - 如何等待请求完成,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17757272/