有相对的CSS定位器Selenium吗? [英] Is there relative CSS locator for Selenium?

查看:243
本文介绍了有相对的CSS定位器Selenium吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我在 #myPage 元素下寻找一些 div 元素。
我的目标是使用CSS选择器,并只限于搜索 #myPage 后代。



使用Selenium XPath定位器类似这样:

  WebElement page = driver.findElement(new By.ById(myPage)); 
....
List< WebElement> item = page.findElements(new By.ByXPath(.// div));但是,尝试使用CSS会在文档中产生所有 divs ,而不仅仅是文档中的 #myPage 的后代:

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

最大的区别是 .// 前缀,使XPath表达式相对。我在CSS语法中找不到类似的属性,我想知道是否可能。



PS

我知道我可以使用 #myPage> div 表达式,但是我将页面查找操作与其后代的查找相结合,这并不总是可取的。

解决方案

此功能尚不存在。在Selectors API第2级中为DOM提出了类似的功能,并在选择器级别4中编码为相对选择器,但我不知道Selenium是否会实现这样的功能。



如果你必须执行相对查找,XPath是你唯一的选择现在。


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.

解决方案

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.

这篇关于有相对的CSS定位器Selenium吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆