使用WebDriverWait替代Thread.sleep()解决Flipkart冰箱筛选加载问题
问题描述
- 测试页面:Flipkart冰箱搜索结果页
- 测试流程:点击Samsung品牌复选框后,页面加载约半秒,随后点击Capacity选项并选择其中一个复选框
- 问题:要求用
WebDriverWait替代Thread.sleep(),但以下等待语句无效果:
wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//div[contains(text(),'Whirlpool')]")));
代码示例
List<WebElement> filterOnProduct = driver.findElements(By.xpath("(//div[@class='_3FPh42'])[1]/div/div")); for(int i=0; i<filterOnProduct.size();i++) { System.out.println(filterOnProduct.get(i).getText()); String fridge = filterOnProduct.get(i).getText(); if(fridge.contains("SAMSUNG")) { filterOnProduct.get(i).click(); break; } } // Thread.sleep(1000); wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//div[contains(text(),'Whirlpool')]"))); JavascriptExecutor js = (JavascriptExecutor) driver; js.executeScript("window.scrollBy(0,250)"); WebElement capacity = driver.findElement(By.xpath("//div[contains(text(),'Capacity')]")); action = new Actions(driver); action.moveToElement(capacity).click().build().perform();
问题原因
你当前等待的Whirlpool元素逻辑完全错误:点击Samsung品牌筛选后,页面仅会展示Samsung的产品,Whirlpool品牌元素要么被过滤不可见,要么根本不会出现在当前筛选结果中,导致等待条件永远无法满足,代码无法继续执行。
解决方案
方案1:直接等待Capacity选项可点击
贴合测试流程,直接等待后续要操作的Capacity元素处于可点击状态:
// 替换原等待语句 WebElement capacity = wait.until(ExpectedConditions.elementToBeClickable(By.xpath("//div[contains(text(),'Capacity')]"))); JavascriptExecutor js = (JavascriptExecutor) driver; js.executeScript("window.scrollBy(0,250)"); action = new Actions(driver); action.moveToElement(capacity).click().build().perform();
方案2:等待页面加载状态结束
如果页面有筛选加载动画,可等待加载图标消失(需替换为实际加载元素的定位):
// 等待加载图标消失,示例XPath需替换为页面实际加载元素定位 wait.until(ExpectedConditions.invisibilityOfElementLocated(By.xpath("//div[@class='_1KfTJK']"))); // 后续操作Capacity JavascriptExecutor js = (JavascriptExecutor) driver; js.executeScript("window.scrollBy(0,250)"); WebElement capacity = wait.until(ExpectedConditions.elementToBeClickable(By.xpath("//div[contains(text(),'Capacity')]"))); action = new Actions(driver); action.moveToElement(capacity).click().build().perform();
方案3:确认Samsung复选框选中状态
先确保Samsung复选框已成功选中,再执行后续操作:
// 点击Samsung后,等待该复选框处于选中状态(替换为实际选中状态的类名) WebElement samsungCheckbox = filterOnProduct.get(i); wait.until(ExpectedConditions.attributeContains(samsungCheckbox, "class", "_30VH1S")); // 后续操作Capacity JavascriptExecutor js = (JavascriptExecutor) driver; js.executeScript("window.scrollBy(0,250)"); WebElement capacity = wait.until(ExpectedConditions.elementToBeClickable(By.xpath("//div[contains(text(),'Capacity')]"))); action = new Actions(driver); action.moveToElement(capacity).click().build().perform();
内容的提问来源于stack exchange,提问作者Codeception
相关产品推荐
相关产品推荐

