Home > Mobile >  How to exclude a single tag or multiple tags while writing an Xpath
How to exclude a single tag or multiple tags while writing an Xpath

Time:10-22

I am writing a xpath and want to get text inside of that element, here is what I am expecting at the end, I want to get the text 1 Schools Found. and exclude the text inside the a tag, that is Clear and here is the xpath I've written but not sure how to exclude/ignore the a tag conent

Here is the HTML


        <p _ngcontent-omv-c171="" class="fs-14 mb-2"> 1 Schools Found. 
            <a _ngcontent-omv-c171="" id="clearSearch" color="dark" 
                   class="btn pmd-btn-link pmd-btn btn-dark pmd-btn-flat" href=""> Clear</a>
       </p>

Here is my implementation, and it is working fine but also getting the text of a tag as I said but don't want it.

Here is my working xpath but getting all the text

//p[@class='fs-14 mb-2']

Here is what I tried to exclude the a tag text but not working

//p[@class='fs-14 mb-2']/*[not(self::a)]

CodePudding user response:

You have to use

//*[@]/text()

To get the text inside of the element.

CodePudding user response:

You can not achieve this with XPath locator only.
When extracting the element text with Selenium it returns you the parent node text with the children elements texts.
There are several approaches to get the parent text only.
One of them is to get the parent element text (containing the children texts as well) and then to remove the children texts from it.
In Java this can be done as following:

/**
 * Takes a parent element and strips out the textContent of all child elements and returns textNode content only
 * 
 * @param e
 *            the parent element
 * @return the text from the child textNodes
 */
public static String getTextNode(WebElement e)
{
    String text = e.getText().trim();
    List<WebElement> children = e.findElements(By.xpath("./*"));
    for (WebElement child : children)
    {
        text = text.replaceFirst(child.getText(), "").trim();
    }
    return text;
}

This method can be called in your case as following:

System.out.println(getTextNode(driver.findElement(By.xpath("//p[@class='fs-14 mb-2']"))));

This can be also done with any other programming language as well.
Credits to JeffC

  • Related