简体   繁体   中英

Selenium java how to get text from element in second quotes ""

<div class="_2b9p7-6Tcy_ja6zEhxML2e">
   <div class="flex _1VLiOJeD-kdBBLC9owCkQr">
    <span class="flex-1">”Total””:”</span>
    <span>
           “USD” 
           “2,175”
    </span>

Need to get the text inly in second quotes "", in this case "“2,175”", and I do not know how to do it. Both “USD” and “2,175” comes from API (they are different every time, hence I can't use driver.findElement(By.xpath("xpath and not 'USD'), I can split the result, and take only the necessary part, but I would like to know a way how to take the value from only the second brackets for the future (2,175). I had performed the following on Intellij

System.out.println(driver.findElement(By.xpath("//div[@class = '_2b9p7-6Tcy_ja6zEhxML2e']//div//span/following-sibling:: span")).getText());

and getting, of course, full text - USD 2,175, but I need 2,175

To extract the value 2,175 you need to induce WebDriverWait for the desired element to be visible and you can use either of the following solutions:

  • Using xpath and following :

     WebElement myElement = new WebDriverWait(driver, 20).until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//span[contains(., 'Total')]//following::span[1]"))); System.out.println(((JavascriptExecutor)driver).executeScript('return arguments[0].lastChild.textContent;', myElement).toString());
  • Using xpath and following-sibling :

     WebElement myElement = new WebDriverWait(driver, 20).until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//span[contains(., 'Total')]//following-sibling::span[1]"))); System.out.println(((JavascriptExecutor)driver).executeScript('return arguments[0].lastChild.textContent;', myElement).toString());
driver.findElement(By.xpath("//div[@class = '_2b9p7-6Tcy_ja6zEhxML2e']//div//span/following-sibling:: span")).getText().substring(7, 11);

You can use substring in two ways:

String substring(int begIndex)

String substring​(int beginIndex, intendIndex)

Hope this helps.

Use split on the returned string like shown below.

String[] amount = returnedText.split(" ");

amount[1] should be your required text.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM