Selenium:Both 等待并在准备就绪时获取元素

Selenium:Both wait and get element when ready

而不是执行 2 个步骤:

wait.until(webDriver -> webDriver.findElement(By.id("userTable")));

然后在准备就绪时检索元素:

WebElement x = webDriver.findElement(By.id("userTable"));

可以一步完成吗?

例如,我不想做 :

wait.until(webDriver -> webDriver.findElement(By.id("userTable")).findElement(By.xpath(".//*[@id=\"userTable\"]/tbody/tr/td[1]/a"))).click();

但想将其分解为多个步骤,因为它更清晰:

首先等待它准备就绪:

wait.until(webDriver -> webDriver.findElement(By.id("userTable")));

然后获取对它的引用:

WebElement x = webDriver.findElement(By.id("userTable"));

然后获取子元素:

x.findElement(By.xpath(".//*[@id=\"userTable\"]/tbody/tr/td[1]/a"))).click();

那么 waitgetting the reference 部分是否可以一步合并?

因为你的用例是调用 click() 你可以诱导 inconjunction with ExpectedConditions for the elementToBeClickable() and you can use either of the following :

  • cssSelector:

    new WebDriverWait(driver, 20).until(ExpectedConditions.elementToBeClickable(By.cssSelector("#userTable>tbody>tr td:nth-child(2)>a"))).click();
    
  • xpath:

    new WebDriverWait(driver, 20).until(ExpectedConditions.elementToBeClickable(By.xpath("//*[@id='userTable']/tbody/tr/td[1]/a"))).click();
    

until 方法 returns <T> 是通用的,基于您在 lambda 表达式中提供的 return 类型。由于 findElement returns WebElementuntil 方法的 return 类型也将是 WebElement.

通过提供的实现,您已经解决了您的问题,因为 until 将 return WebElement 或抛出 TimeoutException

只需保存对变量的引用:

WebElement userTable = wait.until(webDriver -> webDriver.findElement(By.id("userTable")));