定位元素
Watir 最重要的功能之一是它提供了多种定位元素的方式。Watir 的定位 API 旨在易于用户(人类)阅读和理解。元素通过创建选择器哈希表来定位,Watir 将其转换为驱动程序识别元素所需的复杂信息。
特殊情况将在下面重点介绍,但 Watir 定位器
- 接受
String
值用于精确匹配 - 接受
RegExp
值用于部分匹配 - 可以与任何其他 Watir 定位器混合使用
- 可以用来查找第一个匹配的元素,或者作为集合的一部分查找所有匹配的元素
首先,与 Selenium 一样,Watir 支持直接使用 :css
& :xpath
选择器的全部功能。当使用其中任何一个时,它们必须是选择器哈希表中唯一提供的选择器。然而,Watir 的目标是最小化对这些强大定位器的依赖。XPath 特别难以阅读,并且容易以脆弱的方式编写,因此 Watir 鼓励采用“不再使用 XPath!”的方法。
此外,值得注意的是,WebDriver 规范中定义了两个 Watir 不直接支持的定位器,因为它通过其他方式提供了相同的功能。
它们是 :link_text
和 :partial_link_text
。使用 Watir,您可以通过文本定位任何元素,而不仅仅是链接,并且 Watir 已经使用正则表达式支持所有定位器的部分匹配。
标准 Watir 定位器
ID
browser.div(id: "header")
browser.div(id: /header/)
名称
browser.text_field(name: 'new_user_email')
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')
browser.text_field(class: /name/)
文本
# evaluates what is in the DOM, not what a user can see on the page
browser.button(text: "Button 2")
browser.button(text: /Button/)
可见文本
# attempts to evaluate based on what a user can see on the page
browser.button(visible_text: "Button 2")
browser.button(visible_text: /Button/)
数据属性
browser.p(data_type: "ruby-library")
browser.p(data_type: /ruby-library/)
Aria 属性
browser.p(aria_label: "ruby-library")
browser.p(aria_label: /ruby-library/)
有效或自定义属性
browser.link(href: 'non_control_elements.html')
browser.link(href: /non_control_elements.html/)
browser.div(custom_attribute: "foo")
browser.div(custom_attribute: /foo/)
标签
# locate based on the value of the associated label element (not attribute)
browser.text_field(label: 'With text'))
browser.text_field(label: /With text/))
索引
- 这不能用于定位元素集合
- 与其他定位器结合使用时,索引是最后应用的过滤器)
browser.div(index: 2)
存在/不存在/多个类
- 这接受一个字符串或正则表达式值的数组
browser.text_field(class: ['order', 'should', 'matter', 'not'])
browser.text_field(class: ['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)
实现细节
大多数情况下,Watir 可以将选择器哈希转换为单个 XPath 表达式,以快速识别元素。您可以通过查看我们的示例应用程序 XPathify 来了解它的样子。无法做到这一点的情况包括使用 :visible
、:visible_text
或 :index
定位器,或者(有时)定位器值中存在正则表达式。在这种情况下,Watir 会定位可能匹配的元素并对其进行迭代以提供所需的结果。