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?
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"));