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

标签 java selenium webdriver selenium-webdriver

我有一个无法继续进行的情况:

我在页面上有两个按钮(两个按钮都在同一帧中)。我正在为 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/

相关文章:

python - Webdriver 异常 :Process unexpectedly closed with status: 1

testing - Selenium (WebDriver) 看不到 richfaces 模式面板

ruby - 如何使用 Watir 在没有图像的情况下启动 Chrome?

java - 更改浏览器中java小程序使用的java版本

java - Selenium 火狐 - WebDriverException : Reached error page: about:certerror

java - 完全禁用 Java 安全机制?

java - webdriver 是类还是接口(interface)?

javascript - 使用 selenium 从 window.location 获取 url

java - 如何在 Spring Prepared Statement 中传递 Java Date

java - 为什么 mongo-java-driver 不存在 eq?