首页 > 解决方案 > 当可以使用 Selenium 和 Java 找到任何一个元素时如何选择一个元素

问题描述

每个负载的数量按钮设计都不同。我已经确定了它们,但我想在找到任何一个元素时继续。

//select quantity 2
//sometimes button A appear
driver.findElement(By.xpath("//select[@id='quantity']")).click();
Select quantity = new Select(driver.findElement(By.xpath("//select[@id='quantity']")));
quantity.selectByIndex(1); 

//sometimes button B appear
driver.findElement(By.xpath("//select[@id='amt']")).click();
Select amt = new Select(driver.findElement(By.xpath("//select[@id='amt']")));
quantity.selectByIndex(1); 

标签: seleniumselenium-webdriverselectwebdriverwebdriverwait

解决方案


您可以使用findElements()而不是findElement(),这将返回一个 Web 元素列表。

现在,如果大小为1,您的脚本将知道该特定元素存在。如果尺寸 id为 0,则按钮将在 UI 中不可见。

数量按钮是这样的:

List<WebElement> quantityButton = driver.findElements(By.xpath("//select[@id='quantity']"));
if(quantityButton.size()==1){
   quantityButton.get(0).click();
}  

对于 amt 按钮:

List<WebElement> amtButton = driver.findElements(By.xpath("//select[@id='amt']"));
    if(amtButton.size()==1){
       amtButton.get(0).click();
    }  

您可以根据您的要求编写相应的 else 块。

不同的方法是使用 try-catch 块。

让我知道这是否有帮助。


推荐阅读