I'm trying to look for elements by xpath with Selenium's WebDriver:
WebElement element1 = driver.findElement(By.id("someID"));
List<WebElement> xPathElements = element1.findElements((By.xpath("//span[@class='someClass']")));
With this code, I'm getting all the elements with class='someClass' in the DOM.
Only when I add "." at the beginning of the xpath string I get all the elements with class='someClass' that are under element1
element1.findElements((By.xpath(".//span[@class='someClass']")));
What's the sense here? I called findElements
from element1
so by default it should search for elements that are under element1
, Why I must add the "."?
It has got nothing to do with Selenium, it is the way xpath works.
If you have something like //elem xpath will located anywhere in the document. But if you want to search for an element relative to another element or rather a descendant then you have to use a '.' or a dot like .//elem.
.
- select current node
//
- Selects nodes in the document from the current node that match the selection no matter where they are. As current node not specified, will search everywhere.
So .//
means search everywhere inside current node.
In your case:
//span[@class='someClass'] is //span[@class='someClass']
.//span[@class='someClass'] is element1//span[@class='someClass']
See - xpath syntax
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.