为什么在 Selenium 中 xpath 不如 id 或 name 定位器更受欢迎? [英] Why is xpath less preferred than id or name locators in Selenium?

查看:59
本文介绍了为什么在 Selenium 中 xpath 不如 id 或 name 定位器更受欢迎?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

也可以使用 xpath 识别具有唯一 ID/名称的 Web 元素.那么与 By.xpath 相比,使用 By.id/By.name 有什么优势.考虑以下示例.下面是一个网页元素.

A web element that has a unique id/name can be identified using xpath as well. Then what is the advantage in using By.id/By.name over By.xpath. Consider the following example. Below is a web element.

<input id="abc" name="abc" xpath="abc">

这个网页元素可以被识别为:

This web element can be identified as:

  1. By.id("abc");
  2. By.name("abc");
  3. By.xpath(".//*[@id='abc']); 或 By.xpath(".//*[@name='abc']);

我想知道使用 1. 或 2. 比使用 3. 有什么优势?

I want to know what is the advantage of using 1. or 2. over 3.?

推荐答案

正如 Gilles Quenot 所提到的,您不能假设 ID 属性是唯一的,但它曾经是并且注定是唯一的,除非我们谈论的是移动应用程序.在 Web 应用中,ID 是理想的搜索方法,因为它应该是唯一的.

As Gilles Quenot mentioned, you cannot assume that an ID attribute is unique, but it was and is meant to be, unless we're talking about mobile apps. In web app, ID is the ideal search method because it is supposed to be unique.

name 属性通常也是唯一的,但不一定是,而且通常不是.

The name attribute is often also unique, but it is not necessarily expected to be, and often is not.

使用 xpath 的一个缺点是元素可能会在文档中移动,或添加其他项目,并且可能会破坏您的 xpath,具体取决于它的制作方式.至少从理论上讲,使用 ID 的定位器更"不受此类破坏的影响,但正如暗示的那样,没有任何保证.

One disadvantage of using xpath is that an element could be moved in the document, or other items added, and it might break your xpath depending on how it is crafted. In theory, at least, a locator that uses ID would be "more" immune to such breakage, but as was hinted at, nothing is guaranteed.

作为规则,如果唯一 ID 不可用,我将使用 xpath,并且我尝试将其编写为足够通用以抵抗破坏".

As a rule, I will use xpath if a unique ID is not available, and I attempt to write it such that it is generic enough to resist "breakage."

这篇关于为什么在 Selenium 中 xpath 不如 id 或 name 定位器更受欢迎?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆