Conditional XPATH in Selenium WebDriver ? | Selenium Forum
M
Posted on 21/10/2015
Hi Folks,

Can someone suggest me how shall we write XPATH for below Tags.

Lets consider, there is one Div and 3 Span tag. Here we have to write XPATH for only 1 Span which will contain <a>. Position of <a> is getting changed dynamically. <a> could be found with in 1, 2 OR 3 Span Tag. So wherever it occurs, write XPATH only for that valid path.

<Div class='country'>
<Span> US </Span>
<Span> Germany </Span>
<Span> <a> India</a> </Span>
</Div>

Thanks,
Robin

M
Replied on 23/10/2015

xpath= div/span/a

this will go directly where "a" is.


M
Replied on 23/10/2015

As you mentioned :

xpath= div/span/a

this will go directly where "a" is.

----------------------------------------- See, it shall not work -> Reason ? we do not know in which span we are going to have anchor tag. Please have a look on the below scenarios

1. <div>
<span>.......................</span>
<span>.......................</span>
<span> <a>..........</a> </span> Here <a> occurs at 3rd span
</div>

2. <div>
<span> <a>..........</a></span>
<span>.......................</span>
<span>...................... </span> Here <a> occurs at 1st span
</div>

3. <div>
<span>......................</span>
<span> <a>..........</a></span>
<span>...................... </span> Here <a> occurs at 2nd span
</div>

Note -> position of <a> is dynamic, it may occur in any of the three span tag

So as you mentioned, div/span/a. It will not work because

you are not telling in your XPath, in which span you have <a>. If <a> is at 2nd span then your XPATH shall not work bcz u r just telling div/span/a. you did not say span[2]. Could you please say something more about it


M
Replied on 24/10/2015

it will work in practice try it.


M
Replied on 24/10/2015

Hi,

You are right. Xpath -> //div/span/a works. But still I have one doubt. Could you please share as pr my understanding meaningful Xpath should be //div[@class='un-lg']/span[3]/a i..e. span[3] but webdriver is able to identified xpath using //div/span/a but here we are not telling the position of span i.e. 1,2, or 3. So how it is identifying right span without using subscript in span.

if there are 100 span on a page then it shall take longer time if <a> occurs at last that is at 100th position of span. but if we directly say span[100], performance should be much better.

Do not know how default span is working when we do not provide [1],[2] or [3]


M
Replied on 26/10/2015

if you want to know about the workings xpath. here are few resouces.


https://docs.oracle.com/javaee/1.4/tutorial/doc/JAXPXSLT3.html

http://archive.oreilly.com/pub/a/perl/excerpts/system-admin-with-perl/ten-minute-xpath-utorial.html

http://stackoverflow.com/questions/18241029/why-does-my-xpath-query-scraping-html-tables-only-work-in-firebug-but-not-the