microwth
microwth

Reputation: 1066

Selenium:Both wait and get element when ready

Instead of doing 2 steps:

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

and then retrieving the element when it's ready:

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

can this be done in one step?

For instance,I don't want to do :

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

but would like to break it down into steps because it's clearer:

That is first wait fo it to be ready:

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

then get a reference to it:

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

and then get the child element:

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

So can the wait and getting the reference parts be somehow joined in one step?

Upvotes: 1

Views: 461

Answers (2)

Fenio
Fenio

Reputation: 3625

until method returns <T> which is generic and based on return type you provide in the lambda expression. Since findElement returns WebElement, the return type of until method will also be WebElement.

With provided implementation, you already solved your problem as until will return WebElement or throw TimeoutException

Just save the reference to a variable:

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

Upvotes: 2

undetected Selenium
undetected Selenium

Reputation: 193058

As your usecase is to invoke click() you can induce WebDriverWait inconjunction with ExpectedConditions for the elementToBeClickable() and you can use either of the following Locator Strategies:

  • 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();
    

Upvotes: 0

Related Questions