数量按钮的设计在每个负载上都不同。我已经认出了他们 但是我要在找到任何一个元素时继续进行操作。
//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);
答案 0 :(得分:2)
您可以使用docker run -e HOSTNAME=myhostname.mydomain.com -p 8500:8500 my_docker_image
代替findElements()
,这将返回Web元素列表。
现在,如果大小为 1 ,您的脚本将知道存在特定元素。如果尺寸ID为 0 ,则按钮在用户界面中将不可见。
类似这样的数量按钮:
findElement()
对于amt按钮:
List<WebElement> quantityButton = driver.findElements(By.xpath("//select[@id='quantity']"));
if(quantityButton.size()==1){
quantityButton.get(0).click();
}
您可以根据需要编写其他else块。
不同的方法是使用try-catch块。
让我知道是否有帮助。
答案 1 :(得分:1)
cruisepandey已经提供了处理这种情况的逻辑。对于您的所有困惑,您都可以尝试嵌套if..else循环,在该循环中将检查第一个元素size()是否到0
在另一个循环中并检查第二个元素的size()。
if(driver.findElements(By.xpath("//select[@id='quantity']")).size()==0)
{
if(driver.findElements(By.xpath("//select[@id='amt']")).size()>0)
{
driver.findElements(By.xpath("//select[@id='amt']")).get(0).click();
Select amt = new Select(driver.findElement(By.xpath("//select[@id='amt']")));
amt.selectByIndex(1);
}
else
{
System.out.println("None of the elements present")
}
}
else
{
driver.findElements(By.xpath("//select[@id='quantity']")).get(0).click();
Select quantity = new Select(driver.findElement(By.xpath("//select[@id='quantity']")));
quantity.selectByIndex(1);
}
答案 2 :(得分:0)
正如您提到的找到一个元素大概是一个动态元素,您需要为elementToBeClickable()
引入 WebDriverWait ,您可以使用以下定位策略:
使用 xpath :
WebElement element = new WebDriverWait(driver, 10).until(ExpectedConditions.or(
ExpectedConditions.visibilityOfElementLocated(By.xpath("//select[@id='quantity']")),
ExpectedConditions.visibilityOfElementLocated(By.xpath("//select[@id='amt']"))
));
Select amt = new Select(element);
quantity.selectByIndex(1);
使用 cssSelector :
WebElement element = new WebDriverWait(driver, 10).until(ExpectedConditions.or(
ExpectedConditions.visibilityOfElementLocated(By.cssSelector("select#quantity")),
ExpectedConditions.visibilityOfElementLocated(By.cssSelector("select#amt"))
));
Select quantity = new Select(element);
quantity.selectByIndex(1);
答案 3 :(得分:0)
如果只有一个按钮(此处实际上是“选择”是合适的),则可以修改XPath以选择其中一个元素:
WebElement quantityElement = driver.findElement(By.xpath("//select[@id='quantity' or @id='amt']"));
Select quantity = new Select(quantityElement);
quantityElement.click();
quantity.selectByIndex(1);
然后,在屏幕上出现哪个都没关系://select[@id='quantity' or @id='amt']
—它会匹配HTML标记ID。
如果页面中同时存在两个HTML标记,则此方法将无效,但同时只能显示一个。