selenium - 当可以使用 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);
解决方案
您可以使用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 块。
让我知道这是否有帮助。
推荐阅读
- cuda - 分区子组的 Cuda 实现
- bash - -bash:__git_ps1:找不到命令:Mac 用户 Big Sur 11.4
- sql - 如何重写以下 SQL 查询以使其与 HSQLDB 一起使用
- java - Android Studio 中的 Firebase 手机 OTP 验证
- c++ - 生成可能会或可能不会更新的源文件
- linker - Facebook iOS SDK 链接不需要的 AdSupport 库
- sql - 如何从 SQL Server 检索每个用户的最后一次登录?
- iis - ISAPI 过滤器修改 302 响应 - IIS 丢弃请求并放入 HTTPERR - IPv6 / HTTP2.0
- python - 更新团队权限 GitHub API
- html - 是否可以对齐
使它们均匀?