Selenium - 如果已经存在,如何检查和增加下拉值?

Selenium - How to check and increment dropdown value if it is already present?

我正在尝试使用 Selenium Webdriver (Java) 自动化应用程序。我的网络应用程序有一个添加按钮。单击添加按钮后,将启用下拉菜单。如果再次单击,将启用第二个下拉菜单。每个后续下拉列表的 ID 将是 page1、page2、page3.. 等等..

我想做的是当我打开页面时,我需要找出页面中是否已经存在任何下拉菜单,如果是,那么 select 下一个下拉值,然后 select 下拉列表中的值。

这是我当前的代码,我在其中手动 selecting 每个下拉菜单并 selecting 它们各自的值。:

driver.findElement(By.id("addPage")).click();
new Select(driver.findElement(By.id("page0"))).selectByVisibleText("ABCD");
driver.findElement(By.id("addPage")).click();
Thread.sleep(1000);
new Select(driver.findElement(By.id("page1"))).selectByVisibleText("CDEF");
driver.findElement(By.id("addPage")).click();
Thread.sleep(1000);
new Select(driver.findElement(By.id("page2"))).selectByVisibleText("EFGH");
driver.findElement(By.id("addContact")).click();

我会尝试按照以下方式做一些事情,假设页面中没有其他下拉元素(我从你的问题中假设是这种情况)。

try {
driver.findElement(By.tagName("select"))
} catch (NoSuchElementException e) {
//create first dropdown
}

您可以尝试用页面上每个 select 元素的 ID 填充一个数组,然后搜索与模式 "page\d" 匹配的元素的存在,然后从那里开始。

我认为您可以找到以 id 开头的任何 select 元素,从 page 开始,获取 id 属性值并单击下一页的下拉菜单。实施示例:

WebElement existingPage = driver.findElement(By.cssSelector("select[id^=page]"));

String nextPageID = Integer.toString(Integer.parseInt(existingPage.getAttribute("id").replaceAll("\D+", "")) + 1);
Select nextPage = new Select(driver.findElement(By.id("page" + nextPageID)));

并且,正如@Iridann 正确指出的那样,要检查是否存在,请捕获 NoSuchElementException 异常:

try {
    WebElement existingPage = driver.findElement(By.cssSelector("select[id^=page]"));
    // ...
} catch (NoSuchElementException e) {
    // no pages found
}