Reputation: 128
I am using Selenium WebDriver. I have a doubt about the xpath.
If I have the following code example:
<div>
<div>
<div>
<a>
<div>
</div>
</a>
</div>
</div>
</div>
And I want to locate the element which is in the last <div>
. I think I have 2 options with the xpath.
First option is with single slash:
driver.findElement(By.xpath("/div/div/div/a/div")).click();
Second option is using double slash (and here is where I have the doubt).
driver.findElement(By.xpath("//a/div")).click();
Is it going to search in the <a>
directly, but what happens if the html example code was just a part of a bigger code and in this bigger code are more "<a>
"?. Where would this method look exactly?
What happens for example if I do it like this:
driver.findElement(By.xpath("//div")).click();
Would it looks if every <div>
found in the html code?
Upvotes: 0
Views: 2530
Reputation: 22617
First of all, avoiding //
is usually the right thing to do - so, the first expression you show is perfect.
Would it looks if every
<div>
found in the html code?
Yes, exactly. An XPath expression like
//div
will select all div
elements in the document, regardless of where they are.
what happens if the html example code was just a part of a bigger code and in this bigger code are more
<a>
?. Where would this method look exactly?
Then, let us make the HTML "bigger":
<div>
<a>
<p>C</p>
</a>
<div>
<div>
<a>
<div>A</div>
</a>
</div>
<a>
<div>B</div>
</a>
</div>
</div>
As you can see, I have added two more a
elements - only one of them contains a div
element. Assuming this new document as the input, there will now be a difference between
/div/div/div/a/div
which will select only <div>A</div>
as the result, and
//a/div
which will select both <div>A</div>
and <div>B</div>
- because the exact position of a
in the tree is now irrelevant. But none of them will select the first a
element that contains p
.
Upvotes: 2