Selenium 简明教程

Selenium - XPath

我们可以使用 xpath 定位器识别网页上的元素。它基本上是通过 DOM 中的 HTML 节点来查找元素的 XML 路径。一旦在浏览器中打开应用程序,用户便会与页面上的元素进行通信,以设计自动化测试用例。主要目的是借助其属性来找到元素。可以使用 id、xpath 等定位器来检测元素。

We can identify an element on a web page using the xpath locator. It is basically an XML path to locate an element through the HTML nodes in DOM. Once an application is opened in the browser, the user communicates with the elements on the page to design an automation test case. The primary objective is to locate the elements with help of its attributes. This process of detecting elements can be achieved using the locators like id, xpath, and so on.

在 Java 中,findElement(By.xpath("<value of xpath>")) 方法用于检测值为 xpath 的元素。使用此方法,将返回与 xpath 的匹配值匹配的第一个元素。如果不存在具有相同 xpath 值的元素,则会引发 NoSuchElementException。

In Java, the findElement(By.xpath("<value of xpath>")) method is used to detect an element with the value of the xpath. Using this, the first element with the matching value of the xpath is returned. In case there is no element with the same value of the xpath, NoSuchElementException is thrown.

Syntax

Webdriver driver = new ChromeDriver();
driver.findElement(By.xpath("xpath value"));

Rules to Create Xpath Expression

要使用 xpath 定位元素,表达式为 //tagname[@attribute='value']。// 表示当前节点,tagname 指当前节点的标签名,@ 用于属性选择,attribute 指属性名,value 指属性值。

To locate elements with xpath, the expression is //tagname[@attribute='value']. // denotes the present node, tagname refers to the tagname of the current node, @ is used for attribute selection, attribute refers to the attribute name, and value refers to the attribute value.

xpath relativeabsolute 可能有两种变体。绝对 xpath 以 / 符号开头,从根结点开始,直到我们想要定位的元素。但是,如果任何元素路径(从根节点到当前节点之间的中间)的路径发生改变,则现有的绝对 xpath 将无法对元素起作用。

There can be two variants of xpath relative and absolute. The absolute xpath begins with / symbol and starts from the root node up to the element that we want to locate. However, if there is a change in path to any element path(in between from the root to the current node), the existing absolute xpath will not work for an element.

让我们从根节点开始识别下面高亮的元素。

Let us identify the below highlighted element starting from the root node.

selenium xpath 1
Xpath used: /html/body/main/div/div/div[2]/div/ul/li[1]/input

请注意,我们可以通过在 $x("<value of xpath>") 内插入 xpath 值,在控制台中验证 xpath。如果存在匹配项,我们将获得长度值超过 0,否则,它将表示没有与我们使用的 xpath 值匹配的元素。例如,在上面的示例中,我们使用了表达式 $x("/html/body/main/div/div/div[2]/div/ul/li[1]/input"),得到了 length: 1。此外,在悬停在结果上方时,我们会在页面上看到高亮的元素。

Please note, we can validate an xpath in the Console, by inserting the xpath value within $x("<value of xpath>"). In case, there is a matching element, we would get length value more 0, else, it would indicate there is no matching element with xpath value we are using. For example, in the above example, we have used the expression $x("/html/body/main/div/div/div[2]/div/ul/li[1]/input"), which yielded length: 1. Also, on hovering over the result, we would get the highlighted element on the page.

相对 xpath 以 // 符号开头,不从根节点开始。对于上面示例中讨论的同一元素,相对 xpath 值将为 //*[@id='c_bs_1']”。

The relative xpath begins with // symbol and does not start from the root node. For the same element, discussed in the above example, the relative xpath value would be //*[@id='c_bs_1']".

selenium xpath 2

另外,请注意我们刚刚用相对和绝对 xpath 识别的元素的 HTML 代码。

Also, please note the HTML code of the element, we have just identified with the relative and absolute xpath.

selenium xpath 3
<input type="checkbox" id="c_bs_1">

还提供了有助于构建相对 xpath 表达式的函数,如 text()。它用于识别页面上可见文本的元素。

There are also functions available which help to frame relative xpath expressions like text(). It is used to identify an element with the help of the visible text on the page.

让我们借助页面上的可见文本识别高亮的文本 Check Box

Let us identify the highlighted text Check Box with the help of visible text on the page.

selenium xpath 4
Xpath used: //h1[text()='Check Box'].

还提供了有助于构建相对 xpath 表达式的函数,如 starts-with()。它用于识别属性值以特定文本开头的元素。此函数通常用于在每次页面加载时都会更改其值的属性。让我们识别 Main Level 1Main Level 2 标签旁边的两个复选框。

There are also functions available which help to frame relative xpath expressions like starts-with(). 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. Let us identify the two checkboxes beside the Main Level 1 and Main Level 2 labels.

selenium xpath 5
Xpath used: //input[starts-with(@id, 'c_bs')].

在上述示例中,我们看到所使用的 xpath 提供了两个带有 xpath 值的匹配元素,输入 #c_bs_1 和输入 #c_bs_2。

In the above example, we saw that the xpath used yielded two matching elements with xpath values, input#c_bs_1, and input#c_bs_2.

还有可帮助构建相对 xpath 表达式(例如 contains())的函数。它标识元素,其属性值包含实际属性值的一部分文本。此函数通常用于在每次页面加载时都会更改其值的属性。

There are also functions available which help to frame relative xpath expressions like contains(). It identifies an element whose attribute value contains a sub-text of the actual attribute value. This function is normally used for attributes whose value changes on each page load.

让我们使用 contains() 标识 Main Level 2 标签旁的高亮显示复选框。

Let us identify the highlighted checkbox beside the Main Level 2 label using contains().

selenium xpath 6
Xpath used://input[contains(@id, 'bs_2')].

我们可以使用 AND 和 OR 条件创建 xpath,以使属性值为真。

We can create xpath using the AND and OR conditions for the value of attributes to be true.

让我们使用 OR 条件标识 Main Level 2 标签旁的高亮显示复选框。

Let us identify the highlighted checkbox beside the Main Level 2 label using OR condition.

selenium xpath 7
Xpath used: //input[@type='submit' or @id='c_bs_2'].

在上述示例中,我们看到所使用的 xpath 具有 OR 条件,其中 @type='submit' 条件不匹配,但 @id='c_bs_2' 条件匹配。

In the above example, we saw that the xpath used has an OR condition where @type='submit' condition does not match but the @id='c_bs_2' condition matches.

让我们使用 AND 条件标识 Main Level 2 标签旁的高亮显示复选框。

Let us identify the highlighted checkbox beside the Main Level 2 label using AND condition.

selenium xpath 8
Xpath used: //input[@type='checkbox' and @id='c_bs_2'].

在上述示例中,我们看到所使用的 xpath 具有 AND 条件,其中两个属性条件都匹配。

In the above example, we saw that the xpath used has AND condition where both the attribute condition matches.

此外,请注意 Main Level 2 旁边的复选框的 HTML 代码,我们刚刚标识了 xpath。

Also, please note the HTML code of the checkbox beside the Main Level 2, we have just identified xpath.

selenium xpath 9
<input type="checkbox" id="c_bs_2">

我们可以使用以下轴创建 xpath。它表示当前节点后面的所有节点。

We can create xpath using the following axes. It represents all nodes that come after the current node.

selenium xpath 10
Xpath used: //span[@class='plus']//following::input[1]

我们可以使用 following-sibling 轴创建 xpath。它表示上下文节点的后代。兄弟节点与当前节点处于同一级别,并共享其父节点。

We can create xpath using the following-sibling axes. It represents the following siblings of the context node. Siblings are at the same level as the current node and share its parent.

selenium xpath 11
Xpath used: //span[@class='plus']//following-sibling::input[1].

我们可以使用父轴创建 xpath。它表示当前节点的父节点。

We can create xpath using the parent axes. It represents the parent of the current node.

让我们使用父轴标识 Sub Level 1 标签旁的高亮显示复选框。

Let us identify the highlighted checkbox beside the Sub Level 1 label using parent axes.

selenium xpath 12
Xpath used: //*[@id='c_bf_1']//parent::li

此外,请注意 Sub Level 1 旁边的复选框的 HTML 代码,我们刚刚标识了 xpath。

Also, please note the HTML code of the checkbox beside the Sub Level 1, we have just identified xpath.

selenium xpath 13
<input type="checkbox" id="c_bf_1">

我们可以使用子轴创建 xpath。它表示当前节点的子节点。

We can create xpath using the child axes. It represents the child of the current node.

//*[@id='bf_1']//child::input[1].
  1. We can create xpath using the preceding axes. It represents all nodes that come before the current node.

  2. We can create xpath using the self axes. It represents all nodes from the current node.

  3. We can create xpath using the descendant axes. It represents all the descendants from the current node.

Conclusion

这结束了我们对 Selenium XPath 教程的全面讲解。我们首先描述了什么是 xpath,以及如何使用 Selenium 创建 Xpath 表达式的规则。这使你具备了 Selenium XPath 的深入知识。明智的做法是不断实践你所学的内容,并探索与 Selenium 相关的内容,以加深你的理解,扩大你的视野。

This concludes our comprehensive take on the tutorial on Selenium XPath. We’ve started with describing what is an xpath, and rules to create Xpath expressions along with Selenium. This equips you with in-depth knowledge of the Selenium XPath. It is wise to keep practicing what you’ve learned and exploring others relevant to Selenium to deepen your understanding and expand your horizons.