Selenium Webdriver AJAX - 如何等待请求完成

Ven*_*nan 3 java selenium webdriver selenium-webdriver

我有一个场景,我无法继续前进:

我在页面上有两个按钮(两个按钮都在同一个框架中).我使用IteratorButton 1.当我们点击它时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();
Run Code Online (Sandbox Code Playgroud)

如果我使用它Thread.sleep(),它的工作正常.但我不想使用它,因为它不是正确的方法.

button2 id也处于启用状态,我无法使用Wait for the element to be enabled.当执行来到button1.next().click(),i,mediately它将进入下一行,而没有完成循环.如果我在之后打印一些文本button1.next().click(),则会打印5次文本.但不知道为什么按钮没有被点击.

甚至试过隐含的等待,但没有运气.

避免此类问题的最佳方法是什么?

Pet*_*ček 7

正确的方法是明确等待产品添加到购物车.操作完成后页面上有些变化,对吧?所以等待发生变化!显然,我不知道你的网页,但有些事情是这样的:

// 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)));
}
Run Code Online (Sandbox Code Playgroud)

  • @VenkateshLakshmanan [如果这个答案被证明是有用和正确的,请考虑接受它.这样,未来的读者就会知道这个问题已得到解决,而且这个答案是正确且有效的.](http://meta.stackexchange.com/a/5235/184794) (3认同)
  • @VenkateshLakshmanan您能否将此答案标记为您接受的答案?(单击答案左侧的复选标记.) (3认同)