微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

[selenium]相对定位器

前言

Relative Locators,相对定位器,是Selenium 4引入的一个新的定位器,相对定位器根据源点元素去定位相对位置的其它元素。

相对定位方法其实是基于JavaScript的 getBoundingClientRect() 而实现,简单的页面还行,复杂页面中可能会定位到需要相同类型的元素。比如要定位按钮A右边的按钮B,但按钮A右边可能会有许多按钮,相对定位就有可能出问题。

基本方法

  • above
  • below
  • toLeftOf
  • toRightOf
  • near

示例

假设emai输入框元素不好定位,但是password输入框元素容易定位。

from selenium.webdriver.support.relative_locator import locate_with
# 定位email元素,然后取下面的password输入框
elem_email = locate_with(By.TAG_NAME, "input").below({By.ID: "email"})

# 定位submit元素,然后取左边的cancel
cancel_locator = locate_with(By.TAG_NAME, "button").to_left_of({By.ID: "submit"})

# 定位Cancel右边的Submit
submit_locator = locate_with(By.TAG_NAME, "button").to_right_of({By.ID: "cancel"})

# 定位email附近的输入框
email_locator = locate_with(By.TAG_NAME, "input").near({By.ID: "lbl-email"})

# 链式
submit_locator = locate_with(By.TAG_NAME, "button").below({By.ID: "email"}).to_right_of({By.ID: "cancel"})

# 使用locate_with之后还要使用find_element
elem = driver.find_element(elem_email)
elem.click()

参考

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐