python + selenium 常用公共方法封装
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 自动化常用到的一些公共方法的封装。
后续可能会继续更新一些方法进去
python + selenium 常用公共方法封装的更多相关文章
- JS常用公共方法封装
_ooOoo_ o8888888o 88" . "88 (| -_- |) O\ = /O ____/`---'\____ .' \\| |// `. / \\||| : |||/ ...
- Python&Selenium智能等待方法封装
摘要:本篇博文用几行代码展示Python和Selenium做自动化测试时常见的显示等待和封装 # 用于实现智能等待页面元素的出现 # encoding = utf-8 ""&quo ...
- python selenium常用基本方法---H5和键盘鼠标操作
一.模拟手机打开页面(H5测试) from selenium import webdriver mobile_emulation = {'deviceName':'iPhone X'} options ...
- iOS常用公共方法
iOS常用公共方法 字数2917 阅读3070 评论45 喜欢236 1. 获取磁盘总空间大小 //磁盘总空间 + (CGFloat)diskOfAllSizeMBytes{ CGFloat si ...
- iOS 常用公共方法
iOS常用公共方法 1. 获取磁盘总空间大小 //磁盘总空间 + (CGFloat)diskOfAllSizeMBytes{ CGFloat size = 0.0; NSError *error; N ...
- appium安卓自动化的 常用driver方法封装
appium安卓自动化的 常用driver方法封装 做安卓自动化的时候,很多方法写起来会造成代码冗余,把这部分封装起来 ,添加到androidUI工具类里,随时可调用 都放在这个类下面: @Compo ...
- 常用js方法封装
常用js方法封装 var myJs = { /* * 格式化日期 * @param dt 日期对象 * @returns {string} 返回值是格式化的字符串日期 */ getDates: fun ...
- Java&Selenium智能等待方法封装
Java&Selenium智能等待方法封装 ExpectedConditions方法还有很多,自然也可以继续扩展很多 package util; import org.openqa.selen ...
- Java&Selenium 模拟键盘方法封装
Java&Selenium 模拟键盘方法封装 package util; import java.awt.AWTException; import java.awt.Robot; import ...
- Java&Selenium控制滚动条方法封装
Java&Selenium控制滚动条方法封装 package util; import org.openqa.selenium.JavascriptExecutor; import org.o ...
随机推荐
- net Core做一个webApi的简单实例
用NetCore 和Dapper 和mySql做一个简单的实例, 一准备工作 1:VS2017+windos系统,也可以用其他的操作系统和工具 2:一台Cenetos的虚拟机或者虚拟机 二:开始 1: ...
- 27_wbpack_自定义Plugin
Tapable 要想学会自定义Plugin就要先了解Tapable这个库 在我们的wbpack中有两个非常重要的两个类Compiler和Compilation 他们是通过注入插件的方式,来监听webp ...
- Django中的app模型细节TypeError: __init__() missing 1 required positional argument: 'on_delete' 解决办法
TypeError: init() missing 1 required positional argument: 'on_delete' 解决办法 当执行应用app模型迁移时: python man ...
- ansible笔记第二章(ansible-varable变量)
(1)变量类型 1.1在playbook文件中的play使用变量 [root@m01 project1]# cat vars_1.yml - hosts: oldboy vars: - web_p ...
- docker-compose 文件
安装 curl -L https://get.daocloud.io/docker/compose/releases/download/v2.4.1/docker-compose-`uname -s` ...
- 清空kafka全部数据
1.停止机器上的kafka,停止业务系统 docker容器执行命令: docker stop 容器名称 2.删除kafka存储目录(server.properties文件log.dirs配置,默认为& ...
- mysql掉电后重启失败问题
报错 2022-12-07T01:41:02.844533Z 0 [ERROR] InnoDB: Ignoring the redo log due to missing MLOG_CHECKPOIN ...
- vue项目运行出现warnings potentially fixable with the `--fix` option的报错问题
vue-cil3 运行报错 warnings potentially fixable with the `--fix` option. 解决办法:"lint": "vue ...
- vue-vite-ts 新版
Vue 后台管理系统 一.系统创建 1.1.环境检测 $ node -v v18.10.0 $ npm -v 9.1.2 ## 若没有该命令 需要用 npm install -g pnpm 安装 $ ...
- HDLbits——Lfsr5
Build this LFSR. The reset should reset the LFSR to 1 module top_module( input clk, input reset, // ...