定位元素 编辑页面   报告问题

Nerodia 最重要的功能之一是它允许用户以多种方式定位元素。Nerodia 定位 API 旨在让用户(人类)轻松阅读和理解。通过创建选择器关键字来定位元素,Nerodia 将其转换为驱动程序识别元素所需的信息(可能很复杂)。

特殊情况将在下面重点介绍,但 Nerodia 定位器

  1. 接受 String 值以进行精确匹配
  2. 接受已编译的正则表达式值以进行部分匹配
  3. 可以与任何其他 Nerodia 定位器混合使用
  4. 可用于查找第一个匹配元素或作为集合的一部分查找所有匹配元素

首先,与 Selenium 类似,Nerodia 支持直接使用 :css:xpath 选择器的全部功能。当使用其中任何一个时,它们必须是选择器哈希中提供的唯一选择器。然而,Nerodia 的目标是最大程度地减少对这些强大定位器的依赖。特别是 XPath 很难阅读,并且很容易以脆弱的方式编写,因此 Nerodia 鼓励采用“不再使用 XPath!”的方法。

此外,值得注意的是,WebDriver 规范中定义了两个定位器,Nerodia 不直接支持,因为它通过其他方式提供了相同的功能。
这些是 :link_text:partial_link_text。使用 Nerodia,您可以通过文本找到任何元素,而不仅仅是链接,并且 Nerodia 已经通过正则表达式支持所有定位器的部分匹配。

标准 Nerodia 定位器

ID

browser.div(id="header")

名称

browser.text_field(name= 'new_user_email')

标签名称

# while this works:
browser.element(tag_name= 'div')
 
# it is highly recommended to leverage this locator by using the element's associated method:
browser.div

类名称

# This is for locating with a single class only
browser.text_field(class_name='name')

文本

# evaluates what is in the DOM, not what a user can see on the page
browser.button(text= "Button 2")

可见文本

# attempts to evaluate based on what a user can see on the page
browser.button(visible_text="Button 2")

数据属性

browser.p(data_type="python-library")

Aria 属性

browser.p(aria_label= "python-library")

有效或自定义属性

browser.text_field({'aria-labelledby': 'elastic.0'})

标签

# locate based on the value of the associated label element (not attribute)
browser.text_field(label= 'With text'))

索引

  • 这不能用于定位元素集合
  • 当与其他定位器结合使用时,索引是应用的最后一个筛选器)
browser.div(index= 2)

存在/不存在/多个类

  • 这采用字符串值的数组
browser.text_field(class_name=['order', 'should', 'matter', 'not'])
browser.text_field(class_name=['this', '!notthis'])

存在/不存在属性

  • 这采用布尔值
browser.div(data_bar=False)
browser.div(data_foo=True)       

可见

  • 这采用布尔值
browser.div(visible=True)
browser.div(visible=False)

相邻节点

  • 这些不是选择器哈希中的定位器
  • 这些是接受选择器哈希的方法
anchor_element.parent(selectors)

anchor_element.previous_sibling(selectors)
anchor_element.following_sibling(selectors)
anchor_element.siblings(selectors)

anchor_element.child(selectors)
anchor_element.children(selectors)

实现细节

大多数情况下,Nerodia 可以将选择器转换为单个 XPath 表达式,以快速识别元素。您可以通过查看我们的示例应用程序 XPathify 来了解它的样子。无法做到这一点的情况包括使用 :visible:visible_text:index 定位器的情况。在这种情况下,Nerodia 会找到潜在的匹配元素并对其进行迭代以提供请求的结果。

上次更新:2021 年 6 月 09 日