Is there relative CSS locator for Selenium?

2019-05-10 03:46发布

问题:

Suppose I'm looking for some div elements under #myPage element. My goal is to use CSS selectors and limit the search only to #myPage descendants.

Using Selenium XPath locators I can write something like this:

WebElement page = driver.findElement(new By.ById("myPage"));
....
List<WebElement> item = page.findElements(new By.ByXPath(".//div"));

However, trying to use CSS yields all divs in documents, not only descendants of #myPage:

WebElement page = driver.findElement(new By.ById("myPage"));
....
List<WebElement> item = page.findElements(new By.ByCssSelector("div"));

The big difference is the .// prefix that makes the XPath expression relative. I couldn't find similar property in CSS syntax, and I wonder if it's even possible.

P.S.
I know I can use #myPage > div expression, but then I couple the page lookup operation with the lookup of its descendants, which is not always desirable.

回答1:

This functionality doesn't exist yet. There's a similar feature being proposed in Selectors API level 2 for DOM, and codified in Selectors level 4 as relative selectors, but I don't know if Selenium will ever implement such a feature.

If you must perform a relative lookup, XPath is your only option for now.