Selenium2+python自动化63-二次封装(click/send_kesy)

时间:2022-05-07
本文章向大家介绍Selenium2+python自动化63-二次封装(click/send_kesy),主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

前言

我们学了显示等待后,就不需要sleep了,然后查找元素方法用参数化去定位,这样定位方法更灵活了,但是这样写起来代码会很长了,于是问题来了,总不能每次定位一个元素都要写一大堆代码吧?这时候就要学会封装啦!

一、显示等待

1.如果你的定位元素代码,还是这样:driver.find_element_by_id("kw").send_keys("yoyo"),那说明你还停留在小学水平,如何让代码提升逼格呢?

2.前面讲过显示等待相对于sleep来说更省时间,定位元素更靠谱,不会出现一会正常运行,一会又报错的情况,所以我们的定位需与WebDriverWait结合

3.以百度的搜索为例

二、封装定位方法

1.从上面代码看太长了,每次定位写一大串,这样不方便阅读,写代码的效率也低,于是我们可以把定位方法进行封装

2.定位方法封装后,我们每次调用自己写的方法就方便多了

三、封装成类

1.我们可以把send_keys()和click()方法也一起封装,写到一个类里

2.定位那里很多小伙伴弄不清楚lambda这个函数,其实不一定要用这个,我们可以用EC模块的presence_of_element_located()这个方法,参数直接传locator就可以了

3.以下是presence_of_element_located这个方法的源码:

class presence_of_element_located(object):
    """ An expectation for checking that an element is present on the DOM
    of a page. This does not necessarily mean that the element is visible.
    locator - used to find the element
    returns the WebElement once it is located
    """
    def __init__(self, locator):
        self.locator = locator

    def __call__(self, driver):
        return _find_element(driver, self.locator)

四、参考代码

1.把get、find_element、click、send_keys封装成类

# coding:utf-8
from selenium import webdriver
from selenium.common.exceptions import *   # 导入所有的异常类
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.ui import WebDriverWait

class Yoyo(object):
    """基于原生的selenium框架做了二次封装."""
    def __init__(self):
        """启动浏览器参数化,默认启动firefox."""
        self.driver = webdriver.Firefox()

    def get(self, url):
        '''使用get打开url'''
        self.driver.get(url)

    def find_element(self, locator, timeout=10):
        '''定位元素方法封装'''
        element = WebDriverWait(self.driver, timeout, 1).until(EC.presence_of_element_located(locator))
        return element

    def click(self, locator):
        '''点击操作'''
        element = self.find_element(locator)
        element.click()

    def send_keys(self, locator, text):
        '''发送文本,清空后输入'''
        element = self.find_element(locator)
        element.clear()
        element.send_keys(text)

if __name__ == "__main__":
    d = Yoyo()  # 启动firefox
    d.get("https://www.baidu.com")
    input_loc = ("id", "kw")
    d.send_keys(input_loc, "yoyo")   # 输入搜索内容
    button_loc = ("id", "kw")
    d.click(button_loc)           # 点击搜索按钮