[toc]
CSS Selector 使用 CSS 定位元素
CSS Selector
是什么?
[MDN web docs]
CSS selectors define the elements to which a set of CSS rules apply.
[w3schools]
In CSS, selectors are patterns used to select the element(s) you want to style.
CSS Selector 语法
4 个基础选择器
个人认为,CSS Selector
最重要的选择器只有下面 4 个,分别是 tagname 标签名称,标签 id 属性,class 属性,以及其他属性:
- tag
- #id
- .class
- [attribute=value]
这 4 个的各种组合,可以出现丰富、强大的效果。
举几个例子
1 | tag#id |
更多选择器
下面再列几个我常用的选择器。
1 | /*-- 属性的模糊匹配 --*/ |
CSS Selector 还有其他复杂的语法,但上面我们讲到的已经是精华,实用性最强。
更多的见资料 [^1]
Selenium
中的CSS Selector
1 | By by = By.cssSelector(String selector); |
示例:
1 | By.cssSelector("button[id='stop']") |
不能通过文本contains
定位元素的问题
有一点需要特别注意,不能使用 a:contains('Sign in')
。
原因:
- Inner texts
are the actual string patterns that the HTML label shows on the page. - (Not supported by WebDriver)
CSS: The CSS2 contains() function is not in CSS3; however, Selenium supports the superset of CSS1, 2, and 3.
contains() is not part of the current CSS3 specification so it will not work on all browsers, only ones that implemented it before it was pulled.
遇到此种场景,可以使用By by = By.ByXPath(String xpathExpression)
。
xpath 见资料 [^2]
资料
[^1]: CSS Selector 详解:https://www.w3schools.com/cssref/css_selectors.asp
[^2]: CSS Selector 与 xpath 语法比较:https://saucelabs.com/resources/articles/selenium-tips-css-selectors