Home > database >  Selenium: How to get text out of a div
Selenium: How to get text out of a div

Time:12-01

I want to get a text which is inside a div. I tried to find help from other questions, but most of them say .getText() which doesnt exist anymore.

This is the inspect: enter image description here

Im using a chrome extension with which i can copy out the XPath, but it doesnt reads the text inside the div. It copies me this here:

//div[@class='mud-alert-message']

CodePudding user response:

To print the text Die Datei... you can use either of the following Locator Strategies:

  • Using cssSelector and getAttribute("innerHTML"):

    System.out.println(wd.findElement(By.cssSelector("div.mud-alert-message")).getAttribute("innerHTML"));
    
  • Using xpath and getText():

    System.out.println(wd.findElement(By.xpath("//div[@class='mud-alert-message']")).getText());
    

Ideally, to extract the text you have to induce WebDriverWait for the visibilityOfElementLocated() and you can use either of the following Locator Strategies:

  • Using cssSelector and getText():

    System.out.println(new WebDriverWait(driver, 20).until(ExpectedConditions.visibilityOfElementLocated(By.cssSelector("div.mud-alert-message"))).getText());
    
  • Using xpath and getAttribute("innerHTML"):

    System.out.println(new WebDriverWait(driver, 20).until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//div[@class='mud-alert-message']"))).getAttribute("innerHTML"));
    

CodePudding user response:

I believe is something like this:

WebElement element = new WebDriverWait(driver, ...).until(ExpectedConditions.elementToBeXXX(By.LOCATOR_TYPE));
String text = element.getText();
  • Related