gpt4 book ai didi

selenium - 当使用 Selenium 和 Java 可以找到任何一个元素时如何选择一个元素

转载 作者:行者123 更新时间:2023-12-02 20:57:00 25 4
gpt4 key购买 nike

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

//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);

最佳答案

您可以使用 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 block 。

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

请告诉我这是否有帮助。

关于selenium - 当使用 Selenium 和 Java 可以找到任何一个元素时如何选择一个元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55948911/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com