关于相对定位器,Selenium官网文档的介绍
介绍了五种相对定位器:
above, below, left of, right of, near
并给出了例子:
email_locator = locate_with(By.TAG_NAME, "input").above({By.ID: "password"})
其中相对定位器(relative locator)方法(此处即above()
),参数既可以传元素对象也可以传locator。官网的例子统一只用了locator,直接传一个之前定位好的element也是可以的:
origin_element = driver.find_element(By.ID, "password")
email_locator = locate_with(By.TAG_NAME, "input").above(origin_element)
那么,为了更方便地使用这个方法,我们可以在框架中对其进行二次封装
首先观察确定调用时所需要的参数,不妨先把它完整地写出来:
driver.find_element(locate_with(By.TAG_NAME, "input").above({By.ID: "password"}))
由此可以看出,我们需要的参数分别为:
- 目标元素的 by:
By.TAG_NAME
- 目标元素的 value:
"input"
- 原本元素的 by:
By.ID
- 原本元素的 value:
"password"
*目标元素为需要被定位的元素,原本元素为已经定位了的元素
除了以上4个之外,above, below, left of, right of, near
5种位置也可以作为参数以提高代码复用性
到这里就能看出,如果封装成一个 relative_locate()
方法,最简单的调用方式就是:
relative_locate('tag name', 'input', 'id', 'password', 'above').click()
5种位置可以定义成一个字典:
directions = {
'above': 'above',
'below': 'below',
'left': 'to_left_of',
'right': 'to_right_of',
'near': 'near'
}
然后就剩下如何由字典的 value 调用相应的位置方法了,可以用 Python 内置的 getattr() 函数
getattr(locate_with(by, value), directions.get(direction))()
完整的封装代码以及调用如下,仅供参考:
def relative_locate(self, by_target, value_target, by_origin, value_origin, direction):
directions = {
'above': 'above',
'below': 'below',
'left': 'to_left_of',
'right': 'to_right_of',
'near': 'near'
}
origin_element = self.locate(by_origin, value_origin)
return self.driver.find_element(getattr(locate_with(by_target, value_target),
directions.get(direction))(origin_element))
relative_locate('css selector', 'input[name="btnI"]', 'css selector',
'center:nth-child(1) input[name="btnK"]', 'right').click()