[英]How can I get text from element with Selenium webdriver and Java?
[英]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>
需要在第二個引號“”中獲取文本,在本例中為““2,175””,我不知道該怎么做。 “USD”和“2,175”都來自API(它們每次都不同,因此我不能使用driver.findElement(By.xpath("xpath而不是'USD'),我可以拆分結果,並且只取必要的部分,但我想知道如何從未來的第二個括號中獲取值(2,175)。我在 Intellij 上執行了以下操作
System.out.println(driver.findElement(By.xpath("//div[@class = '_2b9p7-6Tcy_ja6zEhxML2e']//div//span/following-sibling:: span")).getText());
當然,得到全文 - 2,175 美元,但我需要 2,175
要提取值2,175,您需要引入WebDriverWait以使所需元素可見,您可以使用以下任一解決方案:
使用xpath和以下內容:
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());
使用xpath和以下兄弟姐妹:
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);
您可以通過兩種方式使用子字符串:
字符串子字符串(int begIndex)
字符串子串 (int beginIndex,intendIndex)
希望這可以幫助。
在返回的字符串上使用 split ,如下所示。
String[] amount = returnedText.split(" ");
amount[1] 應該是你需要的文字。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.