Home > Back-end >  How to validate the text in both p tags
How to validate the text in both p tags

Time:02-22

<p> expanded state:</p>
<P> true </p>

Need to print the text of both tags as one output.

Output as: expanded state: true

CodePudding user response:

If you are struggling to locate 2 identical elements use square brackets and parentheses to specify which tag you are referring to. E.g:

driver.findElement(By.xpath("(//p)[2]"));

This will get the second p tag on the page. To get the text for printing, use the WebElement method .getText() instead. E.g:

String firstElementText = driver.findElement(By.xpath("(//p)[2]")).getText();

Here is working example I made

CodePudding user response:

For what you are displaying as HTML:

String html = "<p> expanded state:</p>\n"  
              "<p> true </p>";
/* A regular expression to remove all html tags 
   and newlines from string and then trim off 
   leading and trailing whitespaces from string.    */
String result = html.replaceAll("\\<.*?\\>", "").replaceAll("\\s ", " ").trim();
System.out.println(result);

Will display in the console window:

expanded state: true
  • Related