2013-07-20 102 views
3

我遇到的情况,我不能够继续进行:硒的webdriver AJAX - 如何等待请求完成

我的页面(这两个按钮都在同一帧)上的两个按钮。我使用Iterator作为Button 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(); 

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

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

即使试过隐含的等待,但没有运气。

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

回答

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))); 
} 
+0

随意问,如果有什么不清楚。 –

+3

@VenkateshLakshmanan [如果这个答案被证明是有用和正确的,考虑接受它。这样,未来的读者会知道这个问题已得到解决,并且这个答案是正确的,并且是正确的。](http://meta.stackexchange.com/a/5235/184794) –

+0

感谢您的回复。其解决。 –