114.md 8.7 KB
Newer Older
W
wizardforcel 已提交
1
# 9M WebDriver – 定位元素:第 3b 部分(`cssSelector`续)
W
init  
wizardforcel 已提交
2 3 4

> 原文: [https://javabeginnerstutorial.com/selenium/9m-webdriver-locating-elements-3b/](https://javabeginnerstutorial.com/selenium/9m-webdriver-locating-elements-3b/)

W
wizardforcel 已提交
5
嗨,忍者! 这篇文章是我们先前文章“[*9l WebDriver – 定位元素:第 3a 部分(由`cssSelector`提供)*](https://javabeginnerstutorial.com/selenium/9l-webdriver-locating-elements-3a/)”的延续。 。 在继续进行操作之前,请确保对它进行了仔细的研究。
W
init  
wizardforcel 已提交
6

W
wizardforcel 已提交
7
使用`cssSelector`定位器的最后两种方法尚待讨论:
W
init  
wizardforcel 已提交
8 9 10 11 12 13

1.  定位子元素
2.  按子字符串匹配

事不宜迟,让我们开始行动吧!

W
wizardforcel 已提交
14
## 定位子元素
W
init  
wizardforcel 已提交
15

W
wizardforcel 已提交
16
也可以使用`cssSelectors`来定位子元素。
W
init  
wizardforcel 已提交
17

W
wizardforcel 已提交
18
让我们考虑一下 HTML 代码,
W
init  
wizardforcel 已提交
19

W
wizardforcel 已提交
20
锚标记是“`div`”的子元素。 要访问子元素,
W
init  
wizardforcel 已提交
21

W
wizardforcel 已提交
22
*使用 ID:*
W
init  
wizardforcel 已提交
23 24 25 26 27

```java
driver.findElement(By.cssSelector("div#child a"));
```

W
wizardforcel 已提交
28
`#`代表“ID”,子元素标签写在空格后面。
W
init  
wizardforcel 已提交
29 30 31 32 33 34 35

*使用类别:*

```java
driver.findElement(By.cssSelector("div.bg_main a"));
```

W
wizardforcel 已提交
36
`.`代表“类”
W
init  
wizardforcel 已提交
37

W
wizardforcel 已提交
38
**示例**:让我们在 Gmail 帐户注册页面上找到名字文本框。
W
init  
wizardforcel 已提交
39

W
wizardforcel 已提交
40
右键点击“名字”文本框,然后选择检查元素,以获取相应的 HTML 代码,如下所示,
W
init  
wizardforcel 已提交
41 42 43 44 45 46 47 48 49

```java
<label id="recovery-email-label">
	<strong>Your current email address</strong>
	<input name="RecoveryEmailAddress" id="RecoveryEmailAddress" value="" 	
               spellcheck="false" type="text">
</label>
```

W
wizardforcel 已提交
50
“标签”标签的子元素可以通过其`input`标签和`name`属性进行访问。
W
init  
wizardforcel 已提交
51 52 53 54 55 56 57

*代码:*

```java
driver.findElement(By.cssSelector("label#recovery-email-label input[name='RecoveryEmailAddress']"));
```

W
wizardforcel 已提交
58
如果父元素具有**多个子元素**(例如下拉列表),并且它们没有“`id`”或“`class`”或此类属性来标识,则“`nth-of-type`”用于定位特定的子元素。
W
init  
wizardforcel 已提交
59

W
wizardforcel 已提交
60
考虑一下 HTML 代码,
W
init  
wizardforcel 已提交
61 62

```java
W
wizardforcel 已提交
63

W
init  
wizardforcel 已提交
64 65 66
   <li>Cat</li>
   <li>Dog</li>
   <li>Birds</li>
W
wizardforcel 已提交
67

W
init  
wizardforcel 已提交
68 69 70 71
```

要标识子元素“狗”,

W
wizardforcel 已提交
72
*代码:*
W
init  
wizardforcel 已提交
73 74 75 76 77 78 79

```java
driver.findElement(By.cssSelector("ul#pets li:nth-of-type(2)"));
```

## 按子字符串匹配

W
wizardforcel 已提交
80
`cssSelectors`也帮助我们使用子字符串来定位元素。
W
init  
wizardforcel 已提交
81

W
wizardforcel 已提交
82
### 匹配前缀(或)开头
W
init  
wizardforcel 已提交
83 84 85

为了匹配具有已知前缀的元素,

W
wizardforcel 已提交
86
**语法**`driver.findElement(By.cssSelector(")tag_name[attribute^='prefix_value_of_attribute']"))`
W
init  
wizardforcel 已提交
87

W
wizardforcel 已提交
88
**解释**:找到以给定前缀开头的元素。 用“`^`”符号表示。
W
init  
wizardforcel 已提交
89 90 91 92 93 94 95

考虑以下代码,

```java
<input value="" name="LastName" id="LastName" spellcheck="false" type="text">
```

W
wizardforcel 已提交
96
我们可以看到`input`标签具有一个名为“`LastName`”的“`id`”属性。 要找到此元素,我们可以指定查找以“`Last`”开头的“`id`”属性值。
W
init  
wizardforcel 已提交
97

W
wizardforcel 已提交
98
*代码:*
W
init  
wizardforcel 已提交
99 100 101 102 103

```java
driver.findElement(By.cssSelector("input[id^='Last']"));
```

W
wizardforcel 已提交
104
### 匹配后缀(或)结尾
W
init  
wizardforcel 已提交
105 106 107

为了匹配具有已知后缀的元素,

W
wizardforcel 已提交
108
**语法**`driver.findElement(By.cssSelector("tag_name[attribute$='suffix_value_of_attribute']"))`
W
init  
wizardforcel 已提交
109

W
wizardforcel 已提交
110
**说明**:找到以给定后缀结尾的元素。 用“`$`”符号表示。
W
init  
wizardforcel 已提交
111 112 113 114 115 116 117

Considering the below code,

```java
<input name="PasswdAgain" id="PasswdAgain" type="password">
```

W
wizardforcel 已提交
118
我们可以看到“`input`”标签的“`name`”属性为“`PasswdAgain`”。 要找到此元素,我们可以指定查找以“`Again`”结尾的“`name`”属性值。
W
init  
wizardforcel 已提交
119

W
wizardforcel 已提交
120
*代码:*
W
init  
wizardforcel 已提交
121 122 123 124 125

```java
driver.findElement(By.cssSelector("input[name$='Again']"));
```

W
wizardforcel 已提交
126
### 匹配一个子字符串
W
init  
wizardforcel 已提交
127 128 129

为了使元素与子字符串匹配,

W
wizardforcel 已提交
130
**语法**`driver.findElement(By.cssSelector("tag_name[attribute*='substring_of_attribute_value']"))`
W
init  
wizardforcel 已提交
131

W
wizardforcel 已提交
132
**说明**:找到包含给定子字符串的元素。 用“`*`”符号表示。
W
init  
wizardforcel 已提交
133 134 135 136 137 138 139

Considering the below code,

```java
<input name="PasswdAgain" id="PasswdAgain" type="password">
```

W
wizardforcel 已提交
140
我们可以看到“`input`”标签的“`name`”属性为“`PasswdAgain`”。 要找到此元素,我们可以指定查找包含“`wdAg`”的“`name`”属性值。
W
init  
wizardforcel 已提交
141

W
wizardforcel 已提交
142
*代码:*
W
init  
wizardforcel 已提交
143 144 145 146 147

```java
driver.findElement(By.cssSelector("input[name*='wdAg']"));
```

W
wizardforcel 已提交
148
## 概览
W
init  
wizardforcel 已提交
149

W
wizardforcel 已提交
150
让我们看一个测试用例,它实现了使用本方法和上一篇文章中介绍的`cssSelector`定位器的不同方法,
W
init  
wizardforcel 已提交
151

W
wizardforcel 已提交
152
**场景**
W
init  
wizardforcel 已提交
153

W
wizardforcel 已提交
154 155 156
1.  打开 Firefox 浏览器。
2.  导航到 Google 帐户创建页面
3.  找到带有 HTML 标签和名称属性的“名字”文本框
W
wizardforcel 已提交
157
4.  输入“`testFirst`”作为名字
W
init  
wizardforcel 已提交
158
5.  在“姓氏”文本框中找到一个以子字符串开头的值
W
wizardforcel 已提交
159
6.  输入“`testLast`”作为姓氏
W
wizardforcel 已提交
160
7.  找到带有 HTML 标签,类型和名称属性的“创建密码”文本框
W
wizardforcel 已提交
161
8.  输入“`Pass1234!`”作为密码
W
init  
wizardforcel 已提交
162
9.  在“确认您的密码”文本框中找到包含子字符串的值
W
wizardforcel 已提交
163
10.  输入“`Pass1234!`”作为确认密码
W
wizardforcel 已提交
164
11.  找到带有 HTML 标签和类别属性的“手机”文本框
W
wizardforcel 已提交
165
12.  输入“`9496543210`”作为电话号码
W
init  
wizardforcel 已提交
166
13.  使用子元素方法找到“当前电子邮件地址”文本框
W
wizardforcel 已提交
167
14.  输入“`...`
W
wizardforcel 已提交
168
15.  验证“JUnit”窗格是否成功,并确认 Eclipse IDE 控制台输出屏幕
W
init  
wizardforcel 已提交
169

W
wizardforcel 已提交
170
此方案的 JUnit 代码是,
W
init  
wizardforcel 已提交
171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244

```java
package com.blog.junitTests;

import java.util.concurrent.TimeUnit;

import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;

public class ElementLocatorTest3 {
        //Declaring variables
        private WebDriver driver; 
        private String baseUrl;

        @Before
        public void setUp() throws Exception{
            // Selenium version 3 beta releases require system property set up
            System.setProperty("webdriver.gecko.driver", "E:\\Softwares\\"
                    + "Selenium\\geckodriver-v0.10.0-win64\\geckodriver.exe");
            // Create a new instance for the class FirefoxDriver
            // that implements WebDriver interface
            driver = new FirefoxDriver();
            // Implicit wait for 5 seconds
            driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
            // Assign the URL to be invoked to a String variable
            baseUrl = "https://accounts.google.com/SignUp";
        }

        @Test
        public void testPageTitle() throws Exception{
            // Open baseUrl in Firefox browser window
            driver.get(baseUrl);
            // Locate 'First Name' text box by cssSelector: tag and name attribute
            // assign it to a variable of type WebElement
            WebElement firstName = driver.findElement(By.cssSelector("input[name='FirstName']"));
            // Clear the default placeholder or any value present
            firstName.clear();
            // Enter/type the value to the text box
            firstName.sendKeys("testFirst");
            //Locate 'Last Name' text box by cssSelector: begins with sub-string
            WebElement lastName = driver.findElement(By.cssSelector("input[id^='Last']"));
            lastName.clear();
            lastName.sendKeys("testLast");
            //Locate password text box by cssSelector: tag and type, name attributes
            WebElement pwd = driver.findElement(By.cssSelector("input[type='Password'][name='Passwd']"));
            pwd.clear();
            pwd.sendKeys("Pass1234!");
            //Locate 'Confirm your password' text box by cssSelector: contains sub-string
            WebElement confirmPwd = driver.findElement(By.cssSelector("input[name*='wdAg']"));
            confirmPwd.clear();
            confirmPwd.sendKeys("Pass1234!");
            // Locate Mobile phone text box by cssSelector: tag and class
            WebElement mobileNum = driver.findElement(By.cssSelector("input.i18n_phone_number_input-inner_input")); 
            mobileNum.clear();
            mobileNum.sendKeys("9496543210");
            //Locate "current email address" text box by cssSelector: child element method
            WebElement recoveryEmail = driver.findElement(By.cssSelector("label#recovery-email-label input[name='RecoveryEmailAddress']"));
            recoveryEmail.clear();
            recoveryEmail.sendKeys("[[email protected]](/cdn-cgi/l/email-protection)");
        }

         @After
          public void tearDown() throws Exception{
            // Close the Firefox browser
            driver.close();
        }
}
```

W
wizardforcel 已提交
245
*执行结果*
W
init  
wizardforcel 已提交
246 247 248 249 250

注释清楚地提供给每行代码,因此是不言自明的。

![by cssSelector output](img/6078cdcb4a983f8f81a8daae42d8ee69.png)

W
wizardforcel 已提交
251
在 JUnit 窗格中,绿色条显示测试用例已成功执行。 另外,控制台窗口中不会记录任何错误。
W
init  
wizardforcel 已提交
252

W
wizardforcel 已提交
253
下图显示了在 Firefox 浏览器中执行的最终输出。
W
init  
wizardforcel 已提交
254 255 256 257 258 259 260

![Browser output](img/1f13c1fe4f6f1394ab62a44476418761.png)

今天的忍者就这些了! 在另一篇文章中再见。

祝你有美好的一天!