Selenium 4 Relative Locators 相对定位器方法的封装

关于相对定位器,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()
  • 3
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值