[selenium4]相对定位器

前言

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()

 

https://www.selenium.dev/documentation/webdriver/elements/locators/

posted @ 2022-08-15 10:44  云long  阅读(200)  评论(0编辑  收藏  举报