This question already has an answer here:

Kindly follow the below HTML code. I want to get the text "DefaultBP" in between the tag. If I using this XPath "//div[@class='workspace']//h1", all the texts including tag such as "Export", "Import", "Tariff List" & "Add Prefix" are displayed. I want only the text "DefaultBP". Hope to hear from you soon.

    <div class="container-fluid">

    <input  type="hidden"  name="addressRuleId"  id="addressRuleId" value="1"/>
            <div class="row text-center">
                    <a href="#" id="exportlink">Export</a>
                    <input type="hidden" id="status" name="status" value="null">
                    <input type="hidden" id="bpCode" name="bpCode" value="defaultbp">
                    <input type="hidden" id="bpName" name="bpName" value="DefaultBP">
                    <input type="hidden" id="addressRuleId" name="addressRuleId" value="1">
                    <a href="#" id="importbasebtn">Import</a> 
                    <!--<a href="/tariffs/import?bpName=DefaultBP">import</a>  -->                   
                     <a id="addprefixbtn" href="/tariffs/add-prefix?bpCode=defaultbp&bpName=DefaultBP&addressRuleId=1">Add Prefix</a>
                    <a href="/tariffs/show-tariffs">Tariff List</a></h1>

marked as duplicate by Alexey R., trashpanda, Bharat Mane, Kate Paulk Aug 29 '18 at 11:11

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.


Try this Xpath

String text = driver.findElement(By.Xpath("//div[@class='row text-center']/following::h1"));
  • getText() is not a function of xpath. Moreover in your xpath you use the text you want to fetch. If you have the text to put to xpath expression why do you need to query exactly the same text.. – Alexey R. Aug 29 '18 at 6:46
  • @AlexeyR. Updated the answer. Please check. – Prasanna venkatesh Aug 29 '18 at 7:11

Given a path PPP that selects the h1 element (for example //div[@class='workspace']//h1, though you haven't shown a workspace div in your input sample), you want


If you have an XPath API that's capable of returning strings rather than nodes, you could use


to get rid of the trailing whitespace.

XXX/text() selects all the child text nodes of an element, that is, the pieces of text that aren't wrapped in further nested elements. In this case you only want the first one, hence [1].


String Default = driver.findElement(By.Xpath("//a[id='addprefixbtn']")).getText();

Try this one

Not the answer you're looking for? Browse other questions tagged or ask your own question.