python + selenium 常用公共方法封装
阅读原文时间:2023年07月08日阅读:3

selenium 环境配置及浏览器驱动的安装:https://www.cnblogs.com/gancuimian/p/16435300.html

uiautomator2 常用公共方法封装见之前的帖子:https://www.cnblogs.com/gancuimian/p/16948536.html

appium 常用公共方法封装见之前的帖子:https://www.cnblogs.com/gancuimian/p/16985527.html

在写(UI)自动化测试用例的时候,最常用的就是方法的调用。我们在这里,把公共方法封装到一个文件中,

这样以后需要使用,直接调用这个方法就可以了。

以下为个人常使用到的一些 selenium 公共方法的封装,(大多都与 appium 的公共方法通用,个别不太一样)

里面有一些操作是有重复的,这个根据个人情况,如果不需要可以不用。重复的话就多个选择,想用哪个用哪个。

首先需要导入/引用到的库

import os,time,faker,random
from typing import Tuple, Union, Dict
from selenium.webdriver import Chrome
from selenium.webdriver.common.by import By
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.support import expected_conditions as when, expected_conditions
from selenium.webdriver import ActionChains,Keys

直接上代码:

class Page:

def \_\_init\_\_(self,driver:Chrome):  
    self.driver = driver

def goto(self,url):  
    """ 去哪个url地址 """  
    # if url.find("https://") != -1:  
    #     return self.browser.get(url)  
    return self.driver.get(url)

def input(self,locator,values):  
    """ 输入框当中输入内容 """  
    el = self.driver.find\_element(\*locator)  
    el.send\_keys(values)

def clear(self, element):  
    """ 清空输入框中的内容 """  
    el = self.driver.find\_element(\*element)  
    el.clear()

def click(self,locator):  
    """ 点击 """  
    # 设置显性等待时间  
    wait = WebDriverWait(self.driver, timeout=8)  
    # 等待某个元素出现并可点击  
    condition = when.element\_to\_be\_clickable(locator)  
    # 定位元素.点击按钮  
    element = wait.until(condition)  
    # 点击元素  
    ActionChains(self.driver).click(element).perform()

def double\_click(self,locator):  
    """ 双击 """  
    # 设置显性等待时间  
    wait = WebDriverWait(self.driver, timeout=10)  
    # 等待某个元素出现并可点击  
    condition = when.element\_to\_be\_clickable(locator)  
    # 定位元素.点击按钮  
    element = wait.until(condition)  
    # 双击元素  
    ActionChains(self.driver).double\_click(element).perform()

def drag\_and\_drop(self,locator1,locator2):  
    """ 拖动 """  
    # 设置显性等待时间  
    wait = WebDriverWait(self.driver, timeout=10)  
    condition = when.element\_to\_be\_clickable(locator1)  
    element1 = wait.until(condition)  
    # 定位到元素1,定位到元素2  
    condition = when.element\_to\_be\_clickable(locator2)  
    element2 = wait.until(condition)  
    # 拖动元素  
    ActionChains(self.driver).drag\_and\_drop(element1,element2).perform()

def is\_element\_exist(self, element: Tuple\[str, Union\[str, Dict\]\], wait\_seconds: int = 10) -> bool:  
    """ 判断元素是否存在 """  
    by = element\[0\]  
    value = element\[1\]

    try:  
        if by == "id":  
            WebDriverWait(self.driver, wait\_seconds, 1).until(expected\_conditions.presence\_of\_element\_located((By.ID, value)))  
        elif by == "name":  
            WebDriverWait(self.driver, wait\_seconds, 1).until(expected\_conditions.presence\_of\_element\_located((By.NAME, value)))  
        elif by == "class":  
            WebDriverWait(self.driver, wait\_seconds, 1).until(expected\_conditions.presence\_of\_element\_located((By.CLASS\_NAME, value)))  
        elif by == "text":  
            WebDriverWait(self.driver, wait\_seconds, 1).until(expected\_conditions.presence\_of\_element\_located((By.LINK\_TEXT, value)))  
        elif by == "partial\_text":  
            WebDriverWait(self.driver, wait\_seconds, 1).until(expected\_conditions.presence\_of\_element\_located((By.PARTIAL\_LINK\_TEXT, value)))  
        elif by == "xpath":  
            WebDriverWait(self.driver, wait\_seconds, 1).until(expected\_conditions.presence\_of\_element\_located((By.XPATH, value)))  
        elif by == "css":  
            WebDriverWait(self.driver, wait\_seconds, 1).until(expected\_conditions.presence\_of\_element\_located((By.CSS\_SELECTOR, value)))  
        elif by == "tag":  
            WebDriverWait(self.driver, wait\_seconds, 1).until(expected\_conditions.presence\_of\_element\_located((By.TAG\_NAME, value)))  
        else:  
            raise NameError("Please enter the correct targeting elements,'id','name','class','text','xpath','css'.")  
    except:  
        return False  
    return True

def get\_element\_text(self,locator):  
    """ 元素定位,获取text文本 """  
    el = self.driver.find\_element(\*locator)  
    return el.text

def is\_text\_exist(self, text: str, wait\_seconds: int = 10) -> bool:  
    """ 判断text是否于当前页面存在 """  
    for i in range(wait\_seconds):  
        if text in self.driver.page\_source:  
            return True  
        time.sleep(1)  
    return False

def is\_loaded(self,url,timeout=8):  
    """ 判断某个 url 是否被加载 """  
    return WebDriverWait(self.driver, timeout).until(when.url\_contains(url))

def get\_element\_attribute(self,locator,expected):  
    """ 获取某个元素的属性 """  
    el = self.driver.find\_element(\*locator)  
    return el.get\_attribute(expected)

def get\_toast\_text(self):  
    """ toast弹窗/获取toast文本内容 """  
    toast = self.driver.find\_element("xpath", "//android.widget.Toast")  
    return toast.text

def emter(self):  
    """ 回车 """  
    return ActionChains(self.driver).send\_keys(Keys.ENTER).perform()

def copy(self):  
    """ 复制快捷键 """  
    actions = ActionChains(self.driver)  
    return actions.key\_down(Keys.CONTROL).send\_keys("c").key\_up(Keys.CONTROL).perform()

def paste(self):  
    """ 粘贴的快捷键 """  
    actions = ActionChains(self.driver)  
    return actions.key\_down(Keys.CONTROL).send\_keys("v").key\_up(Keys.CONTROL).perform()

def set\_attribute(self,locator,name,value):  
    """ 设置元素属性(12306) """  
    el = self.driver.find\_element(\*locator)  
    js = f'arguments\[0\].{name} = f"{value}"'  
    self.driver.execute\_script(js,el)

def switch\_to\_iframe(self,locator,timeout=10):  
    """ 切换iframe """  
    # iframe = self.browser.find\_element(\*locator)  
    # self.browser.switch\_to.frame(iframe)  
    # 使用显性等待 切换 iframe  
    wait = WebDriverWait(self.driver, timeout)  
    wait.until(when.frame\_to\_be\_available\_and\_switch\_to\_it(locator))

def switch\_to\_default(self):  
    """ iframe 切回主页面 """  
    self.driver.switch\_to.default\_content()

def scroll\_to\_bottom(self):  
    """ 滚动到页面底部,使用js操作 """  
    js = "window.scrollTo(0,document.body.scrollHeight)"  
    self.driver.execute\_script(js)

def screenshot(self, name):  
    """ 截图(注释的部分,根据个人需求可增or减) """  
    # day = time.strftime('%Y-%m-%d', time.localtime(time.time()))  
    # fp = "..\\\\Result\\\\" + day  
    fp = ".\\\\images\\\\"      # ".":表示上级; "..":表示上上级

    tm = time.strftime('%Y-%m-%d-%H\_%M', time.localtime(time.time()))  
    if os.path.exists(fp):  
        filename = fp + "\\\\" + tm + '\_' + name + '.png'  
    else:  
        os.makedirs(fp)  
        filename = fp + "\\\\" + tm + '\_' + name + '.png'  
    self.driver.save\_screenshot(filename)

def randmon\_phone(self):  
    """ 随机生成一个手机号,或者其他想生成的数据 """  
    while True:  
        phone = "130"  
        for i in range(8):  
            num = random.randint(0, 9)  
            phone += str(num)  
        return phone

def generate\_phone\_number(self):  
    """ 随机生成手机号(与上面的实现方法一致,写法用了列表推导式) """  
    prefix = "130"  
    suffix = \[random.randint(0, 9) for \_ in range(8)\]  
    return f"{prefix}{''.join(\[str(i) for i in suffix\])}"

def new\_mobile(self):  
    """ 随机生成手机号,需下载:pip install pytest\_facker """  
    fk = faker.Faker(locale=\["zh\_CN"\])  
    return fk.phone\_number()

if __name__ == '__main__':
pass

以上就是本人 selenium 自动化常用到的一些公共方法的封装。

后续可能会继续更新一些方法进去