Selenium 简明教程
Selenium WebDriver - Locator Strategies
一旦应用程序启动,用户就会与页面上的元素进行交互,比如单击链接/按钮、在输入框中输入文本、从下拉选项中选择一个选项等等,以此创建自动测试用例。第一步是借助其属性来识别元素。可以使用定位器来进行此识别,即 id、name、class name、xpath、css、tagname、link text 和 partial link。
Once an application is launched, the user interacts with the elements on the page like clicking a link/button, typing a text within an input box, selecting an option from the dropdown, and so on to create an automation test case. The first task is to identify the elements with help of its attributes. This identification can be done using the locators namely id, name, class name, xpath, css, tagname, link text, and partial link.
Id Locator
元素的 id 属性可用于识别元素。在 Java 中,方法 findElement(By.id("<value of id attribute>")) 用于使用 id 属性的值来查找元素。使用此方法,应该识别出第一个与属性 id 的值匹配的元素。如果没有值类似于 id 属性的元素,则会引发 NoSuchElementException。
The id attribute for an element can be used for its identification. In Java, the method findElement(By.id("<value of id attribute>")) is used to locate an element with the value of the id attribute. Using this, the first element with the matching value of the attribute id should be identified. In case there is no element with the similar value of the id attribute, NoSuchElementException is thrown.
Syntax
Webdriver driver = new ChromeDriver();
driver.findElement(By.id("id value”));
让我们看看在 Name 旁边输入框的 html 代码,在下图中进行了高亮显示:
Let us see the html of the input box beside Name highlighted in the below image −

上图中突出显示的编辑框有一个具有值 name 的 id 属性。让我们尝试在该编辑框中输入文本 Selenium 。
The edit box highlighted in the above image has an id attribute having the value name. Let us make an attempt to enter text Selenium into this edit box.
package org.example;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import java.util.concurrent.TimeUnit;
public class LocatorID {
public static void main(String[] args) throws InterruptedException {
// Initiate the Webdriver
WebDriver driver = new ChromeDriver();
// adding implicit wait of 20 secs
driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);
// Opening the webpage where we will identify edit box enter text
driver.get("https://www.tutorialspoint.com/selenium/practice/selenium_automation_practice.php");
// Identify the search box with id locator then enter text Selenium
WebElement i = driver.findElement(By.id("name"));
i.sendKeys("Selenium");
// Get the value entered
String text = i.getAttribute("value");
System.out.println("Entered text is: " + text);
// Close browser
driver.quit();
}
}
它将显示以下输出 −
It will show the following output −
Entered text is: Selenium
Process finished with exit code 0
输出显示 Process with exit code 0 消息,表示上述代码成功执行。此外,在编辑框中输入的值(从 getAttribute 方法获取) - Selenium 在控制台中收到。
The output shows the message - Process with exit code 0 means that the above code executed successfully. Also, the value entered within the edit box (obtained from the getAttribute method) - Selenium was received in the console.
Name Locator
元素的名称属性可用于识别元素。在 Java 中,方法 findElement(By.name("<value of name attribute>")) 用于使用名称属性的值来查找元素。使用此方法,应该识别出第一个与属性 name 的值匹配的元素。如果没有值类似于 name 属性的元素,则会引发 NoSuchElementException。
The name attribute for an element can be used for its identification. In Java, the method findElement(By.name("<value of name attribute>")) is used to locate an element with value of the name attribute. Using this, the first element with the matching value of the attribute name should be identified. In case there is no element with the similar value of the name attribute, NoSuchElementException is thrown.
Syntax
Webdriver driver = new ChromeDriver();
driver.findElement(By.name("name value"));
让我们调查前面讨论的同一个输入框的 html 代码,如下图所示:
Let us investigate the html code of the same input box as discussed before in the below image −

上图中突出显示的编辑框有一个具有值 name 的名称属性。让我们在该编辑框中输入文本 Selenium 。
The edit box highlighted in the above image has a name attribute having value as name. Let us input the text Selenium into this edit box.
package org.example;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import java.util.concurrent.TimeUnit;
public class LocatorName {
public static void main(String[] args) throws InterruptedException {
// Initiate the Webdriver
WebDriver driver = new ChromeDriver();
// adding implicit wait of 20 secs
driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);
// Opening the webpage where we will identify edit box enter text
driver.get("https://www.tutorialspoint.com/selenium/practice/selenium_automation_practice.php");
// Identify the search box with name locator to enter text
WebElement i = driver.findElement(By.name("name"));
i.sendKeys("Selenium");
// Get the value entered
String text = i.getAttribute("value");
System.out.println("Entered text is: " + text);
// Close browser
driver.quit();
}
}
它将显示以下输出 −
It will show the following output −
Entered text is: Selenium
在编辑框中输入的值 - Selenium 在控制台中打印出来。
The value entered within the edit box - Selenium got printed in the console.
Class Name Locator
元素的类名称属性可用于识别元素。在 Java 中,方法 findElement(By.className("<value of class name attribute>")) 用于使用类名称属性的值来查找元素。使用此方法,将识别出第一个与属性类名称的值匹配的元素。如果没有值类似于名称属性的元素,则会引发 NoSuchElementException。
The class name attribute for an element can be used for its identification. In Java, the method findElement(By.className("<value of class name attribute>")) is used to locate an element with value of the class name attribute. Using this, the first element with the matching value of the attribute class name is identified. In case there is no element with the similar value of the name attribute, NoSuchElementException is thrown.
Syntax
Webdriver driver = new ChromeDriver();
driver.findElement(By.className("class name value"));
让我们看看下图中突出显示的 Click Me 的 html 代码:
Let us see the html code of Click Me highlighted in the below image −

它有一个类名称属性,值为 btn-primary 。单击该元素后,我们将在该页面上获得 You have done a dynamic click 。
It has a class name attribute with value as btn-primary. Click on that element after that we would get the You have done a dynamic click on the page.

package org.example;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import java.util.concurrent.TimeUnit;
public class LocatorClassName {
public static void main(String[] args) throws InterruptedException {
// Initiate the Webdriver
WebDriver driver = new ChromeDriver();
// adding implicit wait of 20 secs
driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);
// Opening the webpage where we will identify button to click
driver.get("https://www.tutorialspoint.com/selenium/practice/buttons.php");
// Identify button with class name to click
WebElement i = driver.findElement(By.className("btn-primary"));
i.click();
// Get text after click
WebElement e = driver.findElement(By.xpath("//*[@id='welcomeDiv']"));
String text = e.getText();
System.out.println("Text is: " + text);
// Closing browser
driver.quit();
}
}
它将显示以下输出 −
It will show the following output −
Text is: You have done a dynamic click
我们已经通过控制台中的信息获取了单击 Click Me 按钮后的文本 - Text is: You have done a dynamic click 。
We had obtained the text after clicking the Click Me button with the message in the console - Text is: You have done a dynamic click.
TagName Locator
元素的标签名可以用于标识元素。在 Java 中,方法 findElement(By.tagName("<tagname 的值>")) 用于定位具有 tagname 值的元素。使用此方法,可以标识出第一个具有匹配 tagname 值的元素。如果不存在具有相似 tagname 值的元素,则会抛出 NoSuchElementException。
The tagname for an element can be used for its identification. In Java, the method findElement(By.tagName("<value of tagname>")) is used to locate an element with the value of the tagname. Using this, the first element with the matching value of the tagname is identified. In case there is no element with the similar value of the tagname, NoSuchElementException is thrown.
Syntax
Webdriver driver = new ChromeDriver();
driver.findElement(By.tagName("tag name value"));
让我们获取 文本 Name 旁边的输入框的 html 代码,如下面的图片所示:
Let us get the html code of the input box beside the text Name as the below image −

上面图片中高亮的输入框具有 input 的标签名。让我们尝试在该输入框中输入文本 Java 。
The input box highlighted in the above image has the tagname as input. Let us make an attempt to enter the text Java in that input box.
package org.example;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import java.util.concurrent.TimeUnit;
public class LocatorTagName {
public static void main(String[] args) throws InterruptedException {
//Initiate the Webdriver
WebDriver driver = new ChromeDriver();
//adding implicit wait of 10 secs
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
// launch a URL
driver.get("https://www.tutorialspoint.com/selenium/practice/selenium_automation_practice.php");
// Identify input box with tagname locator
WebElement t = driver.findElement(By.tagName("input"));
// then enter text
t.sendKeys("Java");
// Get the value entered
String text = t.getAttribute("value");
System.out.println("Entered text is: " + text);
// Closing browser
driver.quit();
}
}
它将显示以下输出 −
It will show the following output −
Entered text is: Java
在编辑框 Java 中输入的值已输出到控制台中。
The value entered within the edit box Java got printed in the console.
Link Text Locator
链接的链接文本可以用于标识该链接。在 Java 中,方法 findElement(By.linkText("<链接文本的值>")) 用于定位具有链接文本值的链接。使用此方法,可以标识出第一个具有匹配链接文本值的元素。如果不存在具有相似链接文本值的元素,则会抛出 NoSuchElementException。该方法最常用于定位网页上的链接。
The link text for a link can be used for its identification. In Java, the method findElement(By.linkText("<value of link text>")) is used to locate a link with the value of the link text. Using this, the first element with the matching value of the link text is identified. In case there is no element with the similar value of the link text, NoSuchElementException is thrown. It is mostly used to locate links on a web page.
Syntax
Webdriver driver = new ChromeDriver();
driver.findElement(By.linkText("value of link text"));
让我们查看下图中高亮的 Created 链接的 html 代码:
Let us see the html code of the link Created highlighted in the below image −

它的链接文本值为 Created 。让我们单击它,然后我们会在页面上获取 Link has responded with status 201 and status text Created 。
It has the link text value as Created. Let us click on it after that we would get the Link has responded with status 201 and status text Created on the page.

package org.example;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import java.util.concurrent.TimeUnit;
public class LocatorLinkText {
public static void main(String[] args) throws InterruptedException {
//Initiate the Webdriver
WebDriver driver = new ChromeDriver();
//adding implicit wait of 10 secs
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
// launch a URL
driver.get("https://www.tutorialspoint.com/selenium/practice/links.php");
// Identify link with tagname link text
WebElement t = driver.findElement(By.linkText("Created"));
// then click
t.click();
// Get the text
WebElement e = driver.findElement(By.xpath("/html/body/main/div/div/div[2]/div[1]"));
String text = e.getText();
System.out.println("Text is: " + text);
// Close browser
driver.quit();
}
}
它将显示以下输出 −
It will show the following output −
Text is: Link has responded with status 201 and status text Created
我们已通过单击 Created 链接并伴有控制台中的消息 - Link has responded with status 201 and status text Created ,来获取文本。
We had obtained the text after clicking the Created link with the message in the console - Link has responded with status 201 and status text Created.
Partial Link Text Locator
链接的部分链接文本可以用于标识链接。在 Java 中,方法 findElement(By.partialLinkText(“<部分链接文本的值>”)) 用于定位具有部分链接文本值的链接。使用此方法,可以标识出第一个具有匹配部分链接文本值的元素。如果不存在具有相似部分链接文本值的元素,则会抛出 NoSuchElementException。该方法最常用于定位网页上的链接。
The partial link text for a link can be used for its identification. In Java, the method findElement(By.partialLinkText(“<value of partial link text>”)) is used to locate a link with the value of the partial link text. Using this, the first element with the matching value of the partial link text is identified. In case there is no element with the similar value of the partial link text, NoSuchElementException is thrown. It is mostly used to locate links on a web page.
Syntax
Webdriver driver = new ChromeDriver();
driver.findElement(By.partialLinkText("partial link text value"));
让我们研究下图中高亮的 Bad Request 链接的 html 代码:
Let us investigate the html code of the link Bad Request highlighted in the below image −

它的链接文本值为 Bad Request 。单击 IT,然后我们将在页面上获取文本 Link has responded with status 400 and status text Bad Request 。
It has the link text value as Bad Request. Click on IT after which we would obtain the text Link has responded with status 400 and status text Bad Request on the page.

package org.example;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import java.util.concurrent.TimeUnit;
public class LocatorPartialLinkText {
public static void main(String[] args) throws InterruptedException {
//Initiate the Webdriver
WebDriver driver = new ChromeDriver();
//adding implicit wait of 10 secs
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
// launch a URL
driver.get("https://www.tutorialspoint.com/selenium/practice/links.php");
// Identify link with tagname partial link text
WebElement t = driver.findElement(By.partialLinkText("Bad"));
// then click
t.click();
// Get the text
WebElement e = driver.findElement(By.xpath("/html/body/main/div/div/div[2]/div[4]"));
String text = e.getText();
System.out.println("Text is: " + text);
// Closing browser
driver.quit();
}
}
它将显示以下输出 −
It will show the following output −
Text is: Link has responded with status 400 and status text Bad Request
我们已通过单击 Bad Request 链接并伴有控制台中的消息 - Link has responded with status 400 and status text Bad Request ,来获取文本。
We had obtained the text after clicking the Bad Request link with the message in the console - Link has responded with status 400 and status text Bad Request.
CSS Locator
元素的 css 定位器值可以用于标识该元素。在 Java 中,方法 findElement(By.cssSelector("<css 选择器的值>")) 用于定位具有 css 选择器值的元素。使用此方法,可以标识出第一个具有匹配 css 选择器值的元素。如果不存在具有相似 css 选择器值的元素,则会抛出 NoSuchElementException。
The css locator value for an element can be used for its identification. In Java, the method findElement(By.cssSelector("<value of css selector>")) is used to locate an element with value of the css selector. Using this, the first element with the matching value of the css selector is identified. In case there is no element with the similar value of the css selector, NoSuchElementException is thrown.
Syntax
Webdriver driver = new ChromeDriver();
driver.findElement(By.cssSelector("value of css selector"));
创建 css 表达式的规则在下面讨论 −
The rules to create a css expression are discussed below −
-
To identify the element with css, the expression should be tagname[attribute='value'].
-
We can also specifically use the id attribute to create a css expression. With id, the format of a css expression should be tagname#id. For example, input#txt [here input is the tagname and the txt is the value of the id attribute].
-
With class, the format of css expression should be tagname.class. For example, input.cls-txt [here input is the tagname and the cls-txt is the value of the class attribute].
-
If there are n children of a parent element, and we want to identify the nth child, the css expression should have nth-of –type(n). Similarly, to identify the last child, the css expression should be ul.reading li:last-child.
对于其值动态变化的属性,我们可以使用 ^= 来查找其属性值以特定文本开头的元素。例如,input[name^='qa'] 其中,input 是标签名,name 属性的值以 qa 开头。
For attributes whose values are dynamically changing, we can use ^= to locate an element whose attribute value starts with a particular text. For example, input[name^='qa'] Here, input is the tagname and the value of the name attribute starts with qa.
对于其值动态变化的属性,我们可以使用 $ = 来查找其属性值以特定文本结尾的元素。例如,input[class $ ='txt'] 其中,input 是标签名,class 属性的值以 txt 结尾。
For attributes whose values are dynamically changing, we can use $ = to locate an element whose attribute value ends with a particular text. For example, input[class $ ='txt'] Here, input is the tagname and the value of the class attribute ends with txt.
对于值动态变化的属性,我们可以使用 = to locate an element whose attribute value contains a specific sub-text. For example, input[name ='nam']。此处,input 是标签名称,而 name 属性的值包含子文本 nam。
For attributes whose values are dynamically changing, we can use = to locate an element whose attribute value contains a specific sub-text. For example, input[name='nam'] Here, input is the tagname and the value of the name attribute contains the sub-text nam.
让我们获取 Name 标签侧面的输入框的 html 代码,如下所示:
Let us get the html code of the input box beside the Name label as given below −

上图中突出显示的编辑框有一个 name 属性,其值为 name ,css 表达式应为 input[name='name'] 。
The edit box highlighted in the above image has a name attribute having the value as name, the css expression should be input[name='name'].
Xpath Locator
元素的 xpath 定位器值可用于其标识。在 Java 中,方法 findElement(By.xpath("<xpath 值>")) 用于使用 xpath 值定位元素。使用此方法,将识别具有匹配 xpath 值的第一个元素。如果没有任何具有类似 xpath 值的元素,则将抛出 NoSuchElementException。
The xpath locator value for an element can be used for its identification. In Java, the method findElement(By.xpath("<value of xpath>")) is used to locate an element with the value of the xpath. Using this, the first element with the matching value of the xpath is identified. In case there is no element with the similar value of the xpath, NoSuchElementException is thrown.
Syntax
Webdriver driver = new ChromeDriver();
driver.findElement(By.xpath("value of xpath”));
要使用 xpath 定位元素,表达式应为 //tagname[@attribute='value']。xpath 有两种类型,分别是相对的和绝对的。绝对 xpath 以 / 符号开头,并从根节点开始到要定位的元素。
To locate the element with xpath, the expression should be //tagname[@attribute='value']. There can be two types of xpath, they are relative and absolute. The absolute xpath starts with / symbol and begins from the root node up to the element to be located.
For example −
For example −
/html/body/div[1]/div[2]/div[1]/input
相对 xpath 以 // 符号开头,不从根节点开始。
The relative xpath begins with // symbol and does not begin from the root node.
For example −
For example −
//img[@alt='TutorialsPoint']
让我们从根开始深入了解突出显示的链接的 html 代码 - Home 。
Let us see the deep dive of the html code of the highlighted link - Home starting from the root.

该元素的绝对 xpath 为:
The absolute xpath for this element is −
/html/body/main/div/div/div[2]/p[1]/a
元素 Home 的相对 xpath 为:
The relative xpath for element Home is −
//a[@href='https://www.tutorialspoint.com/index.htm']
Xpath Functions
还提供有帮助构建相对 xpath 表达式的函数。
There are also functions available which help to frame relative xpath expressions.
text()
它用于定位网页上可见文本的元素。 Home 链接的 xpath 表达式为:
It is used to locate an element with the visible text on the web page. The xpath expression for the Home link is −
//*[text()='Home']
starts-with()
它用于 identification 其属性值以特定文本开头的元素。此函数通常用于在每个页面加载时其值都会发生变化的属性。
It is used to identify an element whose attribute value begins with a specific text. This function is normally used for attributes whose value changes on each page load.
让我们调查链接 Moved 的 html:
Let us investigate the html of the link Moved −

xpath 表达式为:
The xpath expression is −
//a[starts-with(@id, 'mov')].
Conclusion
这结束了我们对 Selenium WebDriver 定位器策略教程的全面介绍。我们从描述 Id 定位器、名称定位器、类名定位器、标签名定位器、链接文本定位器、部分链接文本定位器、CSS 定位器、XPath 定位器以及阐述如何将它们与 Selenium 一起使用的示例开始。这使你具备对 Selenium WebDriver 定位器策略的深入了解。明智之举是继续实践你所学到的内容,并探索与 Selenium 相关的其他内容,以加深你的理解并拓宽你的视野。
This concludes our comprehensive take on the tutorial on Selenium WebDriver Locator Strategies. We’ve started with describing Id Locator, Name Locator, Class Name Locator, TagName Locator, Link Text Locator, Partial Link Text Locator, CSS Locator, Xpath Locator and examples illustrating how to use them along with Selenium. This equips you with in-depth knowledge of the Selenium WebDriver Locator Strategies. It is wise to keep practicing what you’ve learned and exploring others relevant to Selenium to deepen your understanding and expand your horizons.