Selenium4新特性-关联定位策略

 

       Selenium 4 引入了关联元素定位策略(Relative Locators)。这种方式主要是应对一些不好定位的元素,但是其周边相关联的元素比较好定位。实现步骤是先定位周边较容易定位的元素,再根据关联元素定位策略定位到想定位的那个元素。如下以具体案例讲解用法。

      以页面relative_locator1.html为例,用于后续测试用。渲染页面,如图所示。

 

 

 

Above模式

 

    假定“输入用户名”input元素不好定位,而“输入密码”input元素容易定位,此时就可用relative locator的Above模式定位到“输入用户名”input元素。实现通过password input元素获取到username input元素,并且在username输入框输入字符“name1”。代码如下:

#大牛测试qq:2574674466
from
selenium import webdriver from selenium.webdriver.chrome.service import Service from selenium.webdriver.common.by import By from selenium.webdriver.support.relative_locator import locate_with #这是在mac上执行的基于chrome浏览器上的测试,如下driver地址请根据实际情况进行修改。 chrome_driver_server = Service("/Users/xxx/Downloads/chromedriver") driver = webdriver.Chrome(service=chrome_driver_server) #如下是打开本地文件,请根据实际地址进行改写 driver.get("file:///Users/jason118/PycharmProjects/selenium4.0-automation/Chapter4/relative_locator1.html") #通过relative locator的above方式先获取到password input,然后再获取username input. username_locator = locate_with(By.TAG_NAME,"input").above({By.ID: "id_pass"}) username = driver.find_element(username_locator)username.send_keys('name1')

 

 

 

 

Below模式

 

 

以上面html为例,假设“输入密码”input元素不好定位,而“输入用户名”input元素容易定位,则可利用relative locator的Below模式定位到“输入密码”input元素。实现通过username input元素获取到password input元素,并且在password输入框输入字符“password1”。代码如下:

password_locator = locate_with(By.TAG_NAME,"input").below({By.ID: "id_username"})
password = driver.find_element(password_locator)
password.send_keys('daniu')

 

Left of模式

以上面html页面为例,假设“取消”按钮不好定位,而右边的“登录”按钮较容易定位,则可用relative locator的Left of模式定位到“取消”按钮元素。代码如下。

 

cancel_locator = locate_with(By.TAG_NAME,"button").to_left_of({By.ID: "id_login"})
cancel_element = driver.find_element(cancel_locator)
#输出取消按钮
print(cancel_element)

 

Right of模式

 

 

以上面html为例,假设“登录”按钮不好定位,而左边的“取消”按钮较容易定位,则可利用relative locator的Right of模式定位到“登录”按钮元素,代码如下。

#通过relative locator的Right of方式先获取到"取消"按钮,然后再获取"登录"按钮.
login_locator = locate_with(By.TAG_NAME,"button").to_right_of({By.ID: "id_cancel"})

 

Near模式

常用于某些元素与元素之间的相对关系不是很明显,如元素A并不是在元素B的正上方、正下方、正右边、正左边等,可采用Near模式,即在某元素的附近(方圆50px之内)也可被定位到。以上面html为例,如果要定位“输入用户名:”label元素,可以先定位username输入框元素,再使用Near模式定位到label标签,代码如下。

label_username_locator = locate_with(By.TAG_NAME,"label").near({By.ID: "id_username"})
label_username_element = driver.find_element(label_username_locator)
print(label_username_element)

 

Chaining relative locators模式

 

Chaining relative locators模式。意思是目标元素的位置既满足在元素A的“Above”位置,又满足在元素B的“Right of” 位置。以上面html为例,假设“取消”按钮元素不好定位,可以利用这种模式进行定位,需满足“输入密码”label元素的“Below”位置,又满足“登录”按钮元素的“Left of”位置,代码如下。

 

cancel_button_locator = locate_with(By.TAG_NAME,"button").below({By.ID: "id_label2"}).to_left_of({By.ID: "id_login"})
cancel_button_element = driver.find_element(cancel_button_locator)
#输出元素对象
print(cancel_button_element)

 

posted @ 2023-01-22 11:27  大牛测试技术  阅读(118)  评论(0编辑  收藏  举报