Reputation: 125
I'm trying to get the content of an element. I've implemented an explicit wait of 20 seconds before the statement of getting content. But I can't get the content. I can get the content of the element if I use sleep()
for 2 seconds. The code I tried is:
WebDriverWait wait1 = new WebDriverWait(driver,20);
wait1.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("XPath")));
String value = driver.findElement(By.xpath("xpath")).getAttribute("text-content");
System.out.println("Value is : " + value);
Output - Value is :
The code with sleep():
WebDriverWait wait1 = new WebDriverWait(driver,20);
Thread.sleep(2000);
String value = driver.findElement(By.xpath("xpath")).getAttribute("text-content");
System.out.println("Value is : " + value);
Output - Value is : $0.00
I'm not getting the value if I use implicit wait also. It is recommended not to use sleep(). Using explicit wait is always the best practice. Why am I not getting the content of the element using explicit wait?
Upvotes: 2
Views: 491
Reputation: 1996
Can you give a try:
Wait<WebDriver> wait = new FluentWait<WebDriver>((WebDriver) driver).withTimeout(20, TimeUnit.SECONDS).pollingEvery(1, TimeUnit.SECONDS);
wait.until(ExpectedConditions.visibilityOf(driver.findElement(By.xpath("XPath"))));
String value = driver.findElement(By.xpath("xpath")).getAttribute("text-content");
System.out.println("Value is : " + value);
Upvotes: 0
Reputation: 193058
The relevant HTML would have helped us to debug the issue in a better way. However as the desired text contains the $ character so a better approach will be to induce WebDriverWait for the expectation for checking if the given text is present in the element and you can use either of the following solutions:
textToBePresentInElementLocated
:
System.out.println(new WebDriverWait(driver, 20).until(ExpectedConditions.textToBePresentInElementLocated(By.xpath("xpath"), "$")).getAttribute("text-content"));
textToBePresentInElementValue
:
System.out.println(new WebDriverWait(driver, 20).until(ExpectedConditions.textToBePresentInElementValue(By.xpath("xpath"), "$")).getAttribute("text-content"));
Upvotes: 1
Reputation:
What is the error you get? It seems like the element doesn't load properly. There may be some animations going on such as a popup modal closing, table loading etc. Usually, it is ok to put sleeps if you know how long these kinds of animations take.
You can also try fluentwait, but if there are animations going on, you may still get exceptions such as driver not being able to click on an element.
FluentWait:
Wait<WebDriver> fluentWait = new FluentWait<>(driver)
.withTimeout(Duration.ofSeconds(timeout))
.pollingEvery(Duration.ofMillis(500))
.ignoring(NoSuchElementException.class)
.ignoring(StaleElementReferenceException.class);
Upvotes: 0