如何通过 Java 使用 Selenium 从元素中提取文本

How to extract the text from the element using Selenium through Java

如何获取此元素的文本:

<div class="status-value" id="divdoctyp" xpath="1">AADHAAR CARD</div>

我试过了

WebElement doctype= driver.findElement(By.xpath("//div[@id='divdoctyp']"));
String type=doctype.getAttribute("type"); 
String label=doctype.getText();
Thread.sleep(5000);
System.out.print("doctype is "+type +"\n"+label);

要从元素中提取文本 AADHAAR CARD,您必须为 visibilityOfElementLocated() 引入 WebDriverWait,您可以使用以下

  • 使用 cssSelectorgetAttribute():

    System.out.println(new WebDriverWait(driver, 20).until(ExpectedConditions.visibilityOfElementLocated(By.cssSelector("div.status-value#divdoctyp"))).getAttribute("innerHTML"));
    
  • 使用 xpathgetText():

    System.out.println(new WebDriverWait(driver, 20).until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//div[@class='status-value' and @id='divdoctyp']"))).getText());