0

Can you help me write an relative XPath for the below HTML to get the para text 'You are an employer' based on link 'Emp':

<div class = "dummy">
<h2 class="dummy2">
<a class="dum3" href="/model/login/">Emp</a>
</h2>
<p class="govuk-body">You are an employer</p>
kjhughes
  • 106,133
  • 27
  • 181
  • 240
  • Welcome to Stack Overflow. In the future, you should be sure to include an attempt (what you've tried), a description what happened, and what you wished to happen. (The earlier downvote you received was probably due to this missing in your first post.) – kjhughes Oct 18 '19 at 15:35

3 Answers3

0

This XPath,

//a[.="Emp"]/following::p[1]/text()

will select the text of the first p following the a with a string value of "Emp".

kjhughes
  • 106,133
  • 27
  • 181
  • 240
0

This should get the text - You are an employer.

//a[contains(text(),'Emp')]/parent::*/following-sibling::p/text()
Sureshmani Kalirajan
  • 1,938
  • 2
  • 9
  • 18
  • Happy to see an improvement over my existing answer, but this isn't even close: Why use substring containment? It could end up matching on `Employer` too, or `Empathy`, ... Why use a wildcard on the element name? It could easily match `p` or `div` or ... not to mention that it'll match on the string values of *any* element in the document. Why navigate needlessly to parent just to use the `following-sibling` axis rather than justing using the `following` axis? – kjhughes Oct 18 '19 at 16:31
  • @kjhughes you are right, it could match anything with 'Emp' on it. I updated the answer to locate only 'a' element. The reason why using sibling because i don't want to use index p[1]. I believe using index is not reliable if there any multiple ps. In our case, we care about locating the immediate sibling. – Sureshmani Kalirajan Oct 18 '19 at 17:05
  • Don't be squeamish about `p[1]` here; in fact, without it multiple `p` along the given axis might also be selected. (You may be misapplying [this concern regarding first in document vs first child selection](https://stackoverflow.com/q/40743951/290085).) BTW, use `p[1]` to select the first `p` along the axis; use `*[1][self::p]` to get the immediate element that then must be a `p`. – kjhughes Oct 18 '19 at 22:53
-1

I'd traverse the tree using XPATH like this

//a[text() = 'Emp']//..//../p

or

//*[. = 'Emp']//..//../p

Naveen
  • 770
  • 10
  • 22