单元素定位
- var el=element(by.id("userName"));
- var el=element(by.name("passWord"));
- var el=element(by.buttonText("登录")); //文字精确相等
- var el=element(by.cssContainingText('.btn-danger', '删除')); //文字包含
- var el=element(by.xpath('//a[contains(text(),"Grid")]')); //支持xpath
- var el=element(by.className("myclass’")); <span class=" myclass’">ddd</span>
- var el=element(by.model(""));
- var el=element(by.binding(""));
- var el=element(by.repeater(""));
元素数组定位
var els=element.all(by.name("price"));
var els = element.all(by.css(‘myclass’)).get(0);
var els = element.all(by.css(’myclass’)).first();
var els = element.all(by.css(’myclass’)).last();
var els = element.all(by.css(’myclass’)).count();
元素是否在页面上已出现
element(by.css(’myclass’)).isPresent(); //元素是否在页面已出现。
定位API优先次序总结
优先次序 | 8种定位 | css | xpath |
1 | id | [id=””] | [@id=””] |
2 | name | [name=””] | [@name=””] |
3 | 文字 (包括按钮文字和超链接文字) | 不能 | [text()=””] |
4 | 部分文字 (包括按钮部分文字和超链接部分文字) | 不能 | [contains(text(),””)] |
5 | tag type | xxx 例如: | //xxx |
6 | class name | .xxx | [@class=””] |
7 | css | -- | -- |
8 | xpath | -- | -- |
9 | 多属性值定位 | [name=””][value=””] | [@name=”” and @value=””] |
10 | Protractor特有 | cssContainingText() | [@class=”” and text()=””] |
11 | Xpath最常用 |
| //div[@class=”” and value=”” and text()=””] Tag + className + 属性值+ 文字 因为比css多一项“文字”,所以比css强大,但是比css速度慢。 |
12 | Css最常用 | //div.xxx[value=””] Tag + className + 属性值 因为比xpath少一项“文字”,所以比xpath弱一点,但是比xpath速度快。 |
|
等价的Css和Xpath
| Css | Xpath |
等价的Class name | div.111 | 等价的是: //div[contains(@class,”111”)] 而不是: //div[@class=”111”] |
下任意多层 | .111 .222 | //div[@class=”111”]//div[@class=”222”] |
下一层 | .111>.222 | //div[@class=”111”]/div[@class=”222”] |
模糊匹配 | span[title*=”abc”] | //span[contains(@title,”abc”)] |
| input[title^=”abc”] | //input[starts-with(@title,”abc”)] |
| input[title$=”abc”] | //input[ends-with(@title,”abc”)] |
多属性匹配 | a[.xyz][title=”abc”][value=”123”] | //a[@class=”xyz” and @title=”abc” and @value=”123”] |
第n个元素 | Li:first-child | -- |
| Li:nth-child(2) | -- |
| Li:last-child | -- |
| Li:first-of-type | Li[1] |
| Li:nth-of-type(2) | Li[2] |
| Li:last-of-type | Li[3] |
有某属性的元素 | *[title] | //*[@title] |
找弟弟 | div.class1 + div | //div[@class=”class1”]//following-sibling::div[1] |
不包含not | div[.name1][not([style=”display”])] | //div[@class=”name1” and not(@style=”display”)] |
多个选择连接 | Apple[title=””], orange[price=””] | 无 |