Home > Back-end >  Extracting text from <BR> Tag using selenium Java
Extracting text from <BR> Tag using selenium Java

Time:12-02

I'm trying to extract text from
tag. But unfortunately nothing worked for me.

<div id="sign_in" >
    <h4>usernames lists:</h4>
    user_1
    <br>
    user_2
    <br>
    user_3
    <br>
    user_4
    <br>
</div>

I'm trying to get it in the list and then extract text.

List <WebElement> li = driver.findElements(By.xpath("//div[@class='sign_in']/br"));
    for(int i=0;i<li.size();i  ) {
        
        System.out.println(li.get(i).getText());
    }

CodePudding user response:

<br> is not a closed tag, it can not hold any text. It's just line separator, see https://www.w3schools.com/tags/tag_br.asp.

This will do the job:

WebElement signIn = driver.findElement(By.id("sign_in"));
String signInFullText = signIn.getText();
String[] splitted = signInFullText.split("\\r?\\n|\\r");
for (String s: splitted) {
    if (!s.equals("usernames lists:")) {
        System.out.println(s);
    }
}

CodePudding user response:

You can try using the below method String[] splitted = str.split("<br>|<br/>"); regex. Because the html tag can be <br/> or <br>

String str = "<div id=\"sign_in\" class=\"sign_in\">"
          "    <h4>usernames lists:</h4>"
          "    user_1"
          "    <br>"
          "    user_2"
          "    <br>"
          "    user_3"
          "    <br>"
          "    user_4\r\n"
          "    <br>\r\n"
          "</div>";

String[] splitted = str.split("<br>|<br/>");
System.out.println(Arrays.toString(splitted));

Sample output :

[<div id="sign_in" >
    <h4>usernames lists:</h4>
    user_1
    , 
    user_2
    , 
    user_3
    , 
    user_4
    , 
</div>]
  • Related