【selenium学习中级篇 -20】封装BasePage基础类

云之高水之远 2020-05-27

【selenium学习中级篇 -20】封装BasePage基础类

 在Base包中新建一个BasePage.py 这个文件中,主要封装一些基础的操作,比如说打开url,关闭浏览器,点击,输入,获取元素等与业务逻辑无关的最底层的操作

这个类,可以根据不同的项目需求进行拓展,本文只是举了一个简单的例子

class BasePage(object):
    def __init__(self, driver):
        self.driver = driver

    # 打开url
    def get_url(self, url):
        self.driver.get(url)

    # 退出浏览器
    def quit_browser(self):
        self.driver.quit()

    # 获取元素
    def find_element(self, selector):
        element = ‘‘
        if ‘=>‘ not in selector:
            return selector.driver.find_element_by_xpath(selector)
        selector_by = selector.split(‘=>‘)[0]
        selector_value = selector.split(‘=>‘)[1]
        if selector_by == ‘id‘:
            element = self.driver.find_element_by_id(selector_value)
        elif selector_by == ‘name‘:
            element = self.driver.find_element_by_name(selector_value)
        elif selector_by == ‘xpath‘:
            element = self.driver.find_element_by_xpath(selector_value)
        elif selector_by == ‘linkText‘:
            element = self.driver.find_element_by_link_text(selector_value)
        elif selector_by == ‘partialLinkText‘:
            element = self.driver.find_element_by_partial_link_text(selector_value)
        elif selector_by == ‘css‘:
            element = self.driver.find_element_by_css_selector(selector_value)

        return element

    # 输入字符
    def type(self, selector, text):
        el = self.find_element(selector)
        el.clear()
        el.send_keys(text)

    # 清空
    def clear(self, selector):
        el = self.find_element(selector)
        el.clear()

    # 点击操作
    def click(self, selector):
        el = self.find_element(selector)
        el.click()

    # 获取页面title
    def get_page_title(self):
        return self.driver.title

    # 获取当前页面的url
    def get_page_url(self):
        return self.driver.current_url

相关推荐