Python代码实现,appium自动化测试框架,核心代码类文件封装 您所在的位置:网站首页 appium框架详解 Python代码实现,appium自动化测试框架,核心代码类文件封装

Python代码实现,appium自动化测试框架,核心代码类文件封装

#Python代码实现,appium自动化测试框架,核心代码类文件封装| 来源: 网络整理| 查看: 265

Python代码实现,appium自动化测试框架,核心代码类文件封装

这个示例将涵盖以下主题:

Appium初始化和设置AppiumDriver类和DesiredCapabilities元素查找和交互错误处理和异常一些好用的工具类

以下是示例代码:

```python # 导入需要用到的库 import os from appium import webdriver from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC from selenium.webdriver.common.by import By from selenium.common.exceptions import TimeoutException, NoSuchElementException # 定义常量 APP_PACKAGE = 'com.example.app' APP_ACTIVITY = '.MainActivity' # 设置DesiredCapabilities desired_capabilities = { 'platformName': 'Android', # 指定平台(iOS或Android) 'platformVersion': '11.0', # 指定版本号 'deviceName': 'emulator-5554', # 指定设备名称 'appPackage': APP_PACKAGE, # 指定应用包名 'appActivity': APP_ACTIVITY, # 指定应用入口Activity 'autoGrantPermissions': True, # 自动授予权限 'noReset': True, # 不重置应用 } class AppiumDriver: """ Appium驱动核心类,封装了许多Appium驱动所用的方法 """ def __init__(self): """ 初始化Appium驱动 """ self.driver = webdriver.Remote('http://localhost:4723/wd/hub', desired_capabilities) def __del__(self): """ 退出Appium驱动并释放资源 """ self.driver.quit() def find_element(self, locator, timeout=10): """ 通过元素定位器查找单个元素 :param locator: 元素定位器,格式为(By.XXX, 'value'),比如(By.ID, 'com.example.app:id/btn_login') :param timeout: 超时时间,默认为10秒 :return: 找到的单个元素对象 """ try: element = WebDriverWait(self.driver, timeout).until(EC.presence_of_element_located(locator)) except (TimeoutException, NoSuchElementException): raise ValueError(f'找不到元素:{locator}') return element def find_elements(self, locator, timeout=10): """ 通过元素定位器查找多个元素 :param locator: 元素定位器,格式为(By.XXX, 'value'),比如(By.ID, 'com.example.app:id/btn_login') :param timeout: 超时时间,默认为10秒 :return: 找到的多个元素对象,返回一个列表 """ try: elements = WebDriverWait(self.driver, timeout).until(EC.presence_of_all_elements_located(locator)) except (TimeoutException, NoSuchElementException): raise ValueError(f'找不到元素:{locator}') return elements def find_element_by_text(self, text, timeout=10): """ 通过元素文本查找单个元素 :param text: 元素文本 :param timeout: 超时时间,默认为10秒 :return: 找到的单个元素对象 """ locator = (By.XPATH, f'//*[contains(@text,"{text}")]') return self.find_element(locator, timeout) def find_elements_by_text(self, text, timeout=10): """ 通过元素文本查找多个元素 :param text: 元素文本 :param timeout: 超时时间,默认为10秒 :return: 找到的多个元素对象,返回一个列表 """ locator = (By.XPATH, f'//*[contains(@text,"{text}")]') return self.find_elements(locator, timeout) def click(self, selector): """ 点击元素 :param selector: 元素,可以是元素对象、元素定位器,或者是元素文本 """ if isinstance(selector, tuple): element = self.find_element(selector) elif isinstance(selector, str): element = self.find_element_by_text(selector) else: element = selector element.click() def send_keys(self, selector, value): """ 在元素中输入文本 :param selector: 元素,可以是元素对象、元素定位器,或者是元素文本 :param value: 要输入的文本 """ if isinstance(selector, tuple): element = self.find_element(selector) elif isinstance(selector, str): element = self.find_element_by_text(selector) else: element = selector element.send_keys(value) # 使用示例 if __name__ == '__main__': driver = AppiumDriver() # 点击登录按钮 login_button = (By.ID, 'com.example.app:id/btn_login') driver.click(login_button) # 输入用户名和密码 username = (By.ID, 'com.example.app:id/et_username') password = (By.ID, 'com.example.app:id/et_password') driver.send_keys(username, 'test') driver.send_keys(password, '123456') # 点击确认登录按钮 confirm_button = '登录' driver.click(confirm_button)

```

这个示例只是一个开始,Appium自动化测试框架的学习深度和广度非常广泛,我希望这个示例可以为你提供一些灵感和启示,让你能够深入了解Appium自动化测试框架的工作原理和实践。

更多实例

实例化一个driver对象并打开APP pythonfrom appium import webdriver desired_caps = { "platformName": "Android", "platformVersion": "8.0", "deviceName": "Android Emulator", "appPackage": "com.example.app", "appActivity": ".MainActivity" } driver = webdriver.Remote("http://localhost:4723/wd/hub", desired_caps) 查找元素并点击 pythonfrom appium.webdriver.common.mobileby import MobileBy from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC # 点击“登录”按钮 login_button = WebDriverWait(driver, 10).until( EC.element_to_be_clickable((MobileBy.ID, "com.example.app:id/login_button")) ) login_button.click() 查找元素并输入文本 python# 输入用户名 username_field = WebDriverWait(driver, 10).until( EC.presence_of_element_located((MobileBy.ID, "com.example.app:id/username_field")) ) username_field.send_keys("my_username") # 输入密码 password_field = WebDriverWait(driver, 10).until( EC.presence_of_element_located((MobileBy.ID, "com.example.app:id/password_field")) ) password_field.send_keys("my_password") 查找元素并获取文本 python# 获取登录成功后的提示信息 success_message = WebDriverWait(driver, 10).until( EC.presence_of_element_located((MobileBy.ID, "com.example.app:id/success_message")) ) print(success_message.text) 查找多个元素并遍历操作 python# 获取所有的菜单项 menu_items = driver.find_elements_by_id("com.example.app:id/menu_item") # 遍历所有的菜单项并点击 for item in menu_items: item.click() 滑动操作 pythonfrom appium.webdriver.common.touch_action import TouchAction # 向上滑动屏幕 action = TouchAction(driver) action.press(x=500, y=1000).move_to(x=500, y=500).release().perform() 等待元素出现并截图 python# 等待成功提示信息出现 success_message = WebDriverWait(driver, 10).until( EC.presence_of_element_located((MobileBy.ID, "com.example.app:id/success_message")) ) # 截图 driver.save_screenshot("success.png") 获取屏幕尺寸并计算坐标 python# 获取屏幕尺寸 screen_size = driver.get_window_size() # 计算坐标 x = int(screen_size["width"] * 0.5) y = int(screen_size["height"] * 0.8) # 点击坐标 driver.tap([(x, y)]) 切换到webview并操作 python# 切换到webview webview = driver.contexts[-1] driver.switch_to.context(webview) # 查找元素并点击 login_button = WebDriverWait(driver, 10).until( EC.element_to_be_clickable((MobileBy.CSS_SELECTOR, "button.login")) ) login_button.click() # 切换回native native = driver.contexts[0] driver.switch_to.context(native) 执行JavaScript代码 python# 执行JavaScript代码 driver.execute_script("window.scrollTo(0, document.body.scrollHeight);") 查找元素并长按 python# 长按元素 element = driver.find_element_by_id("com.example.app:id/long_press_element") action = TouchAction(driver) action.long_press(element).release().perform() 查找元素并拖拽 python# 拖拽元素 source_element = driver.find_element_by_id("com.example.app:id/source_element") target_element = driver.find_element_by_id("com.example.app:id/target_element") action = TouchAction(driver) action.long_press(source_element).move_to(target_element).release().perform() 查找元素并右滑 python# 右滑元素 element = driver.find_element_by_id("com.example.app:id/swipe_element") action = TouchAction(driver) action.press(element).move_to(x=600, y=0).release().perform() 查找元素并左滑 python# 左滑元素 element = driver.find_element_by_id("com.example.app:id/swipe_element") action = TouchAction(driver) action.press(element).move_to(x=-600, y=0).release().perform() 查找元素并上滑 python# 上滑元素 element = driver.find_element_by_id("com.example.app:id/swipe_element") action = TouchAction(driver) action.press(element).move_to(x=0, y=-600).release().perform() 查找元素并下滑 python# 下滑元素 element = driver.find_element_by_id("com.example.app:id/swipe_element") action = TouchAction(driver) action.press(element).move_to(x=0, y=600).release().perform() 查找元素并缩放 python# 缩放元素 element = driver.find_element_by_id("com.example.app:id/zoom_element") action = TouchAction(driver) action.press(element).move_to(x=0, y=-200).move_to(x=0, y=-200).move_to(x=0, y=-200).release().perform() 查找元素并旋转 python# 旋转元素 element = driver.find_element_by_id("com.example.app:id/rotate_element") action = TouchAction(driver) action.press(element).move_to(x=0, y=-200).move_to(x=0, y=-200).move_to(x=0, y=-200).release().perform() 查找元素并放大 python# 放大元素 element = driver.find_element_by_id("com.example.app:id/pinch_element") action1 = TouchAction(driver) action2 = TouchAction(driver) action1.press(element).move_to(x=100, y=-100).release() action2.press(element).move_to(x=-100, y=100).release() multi_action = MultiAction(driver) multi_action.add(action1, action2) multi_action.perform() 查找元素并缩小 python# 缩小元素 element = driver.find_element_by_id("com.example.app:id/pinch_element") action1 = TouchAction(driver) action2 = TouchAction(driver) action1.press(element).move_to(x=-100, y=100).release() action2.press(element).move_to(x=100, y=-100).release() multi_action = MultiAction(driver) multi_action.add(action1, action2) multi_action.perform() 查找元素并获取属性值 python# 获取元素属性值 element = driver.find_element_by_id("com.example.app:id/element") value = element.get_attribute("value") print(value) 查找元素并判断是否可见 python# 判断元素是否可见 element = driver.find_element_by_id("com.example.app:id/element") visible = element.is_displayed() print(visible) 查找元素并判断是否启用 python# 判断元素是否启用 element = driver.find_element_by_id("com.example.app:id/element") enabled = element.is_enabled() print(enabled) 查找元素并判断是否选中 python# 判断元素是否选中 element = driver.find_element_by_id("com.example.app:id/element") selected = element.is_selected() print(selected) 查找元素并清除文本内容 python# 清除文本内容 element = driver.find_element_by_id("com.example.app:id/element") element.clear() 查找元素并提交表单 python# 提交表单 element = driver.find_element_by_id("com.example.app:id/element") element.submit() 查找元素并执行单击操作 python# 单击元素 element = driver.find_element_by_id("com.example.app:id/element") element.click() 查找元素并执行双击操作 python# 双击元素 element = driver.find_element_by_id("com.example.app:id/element") action = TouchAction(driver) action.tap(element).tap(element).perform() 查找元素并执行长按操作 python# 长按元素 element = driver.find_element_by_id("com.example.app:id/element") action = TouchAction(driver) action.long_press(element).release().perform() 查找元素并执行拖拽操作 python# 拖拽元素 source_element = driver.find_element_by_id("com.example.app:id/source_element") target_element = driver.find_element_by_id("com.example.app:id/target_element") action = TouchAction(driver) action.long_press(source_element).move_to(target_element).release().perform() 查找元素并执行滚动操作 python# 滚动元素 element = driver.find_element_by_id("com.example.app:id/element") driver.execute_script("arguments[0].scrollIntoView();", element) 查找元素并执行选择操作 python# 选择元素 element = driver.find_element_by_id("com.example.app:id/element") select = Select(element) select.select_by_visible_text("Option 1") 查找元素并执行上传文件操作 python# 上传文件 element = driver.find_element_by_id("com.example.app:id/element") element.send_keys("/path/to/file") 查找元素并执行下载文件操作 python# 下载文件 element = driver.find_element_by_id("com.example.app:id/element") url = element.get_attribute("href") urllib.request.urlretrieve(url, "/path/to/file") 查找元素并执行截图操作 python# 截图元素 element = driver.find_element_by_id("com.example.app:id/element") location = element.location size = element.size driver.save_screenshot("screenshot.png") image = Image.open("screenshot.png") left = location["x"] top = location["y"] right = location["x"] + size["width"] bottom = location["y"] + size["height"] image.crop((left, top, right, bottom)).save("element.png") 查找元素并执行刷新操作 python# 刷新页面 driver.refresh() 查找元素并执行返回操作 python# 返回上一页 driver.back() 查找元素并执行前进操作 python# 前进到下一页 driver.forward() 查找元素并执行最大化操作 python# 最大化窗口 driver.maximize_window() 查找元素并执行最小化操作 python# 最小化窗口 driver.minimize_window() 查找元素并执行全屏操作 python# 全屏窗口 driver.fullscreen_window() 查找元素并执行退出操作 python# 退出驱动 driver.quit() 查找元素并执行关闭操作 python# 关闭窗口 driver.close() 查找元素并执行切换到iframe操作 python# 切换到iframe iframe = driver.find_element_by_id("iframe") driver.switch_to.frame(iframe) 查找元素并执行切换到默认内容操作 python# 切换到默认内容 driver.switch_to.default_content() 查找元素并执行切换到父级iframe操作 python# 切换到父级iframe driver.switch_to.parent_frame() 查找元素并执行切换到弹出窗口操作 python# 切换到弹出窗口 window_handle = driver.window_handles[-1] driver.switch_to.window(window_handle) 查找元素并执行切换到默认窗口操作 python# 切换到默认窗口 driver.switch_to.window(driver.window_handles[0]) 查找元素并执行获取当前窗口句柄操作 python# 获取当前窗口句柄 window_handle = driver.current_window_handle print(window_handle) 查找元素并执行获取所有窗口句柄操作 python# 获取所有窗口句柄 window_handles = driver.window_handles print(window_handles) 查找元素并执行获取当前url操作 python# 获取当前url url = driver.current_url print(url) 查找元素并执行获取页面源代码操作 python# 获取页面源代码 source = driver.page_source print(source) 查找元素并执行获取cookie操作 python# 获取cookie cookie = driver.get_cookies() print(cookie) 查找元素并执行添加cookie操作 python# 添加cookie driver.add_cookie({"name": "cookie_name", "value": "cookie_value"}) 查找元素并执行删除cookie操作 python# 删除cookie driver.delete_cookie("cookie_name") 查找元素并执行删除所有cookie操作 python# 删除所有cookie driver.delete_all_cookies() 查找元素并执行等待操作 python# 等待元素出现 element = WebDriverWait(driver, 10).until( EC.presence_of_element_located((MobileBy.ID, "com.example.app:id/element")) ) 查找元素并执行显示等待操作 python# 显示等待元素出现 element = WebDriverWait(driver, 10).until( EC.visibility_of_element_located((MobileBy.ID, "com.example.app:id/element")) ) 查找元素并执行可点击等待操作 python# 可点击等待元素出现 element = WebDriverWait(driver, 10).until( EC.element_to_be_clickable((MobileBy.ID, "com.example.app:id/element")) ) 查找元素并执行隐式等待操作 python# 隐式等待元素出现 driver.implicitly_wait(10) 查找元素并执行断言操作 python# 断言元素是否存在 assert driver.find_element_by_id("com.example.app:id/element") 查找元素并执行判断操作 python# 判断元素是否存在 if driver.find_elements_by_id("com.example.app:id/element"): print("元素存在") else: print("元素不存在") 查找元素并执行循环操作 python# 循环操作 while True: element = driver.find_element_by_id("com.example.app:id/element") if element.is_displayed(): element.click() break else: driver.swipe(100, 1000, 100, 500) 查找元素并执行条件分支操作 python# 条件分支操作 element = driver.find_element_by_id("com.example.app:id/element") if element.is_displayed(): element.click() else: driver.swipe(100, 1000, 100, 500) 查找元素并执行异常处理操作 python# 异常处理操作 try: element = driver.find_element_by_id("com.example.app:id/element") element.click() except NoSuchElementException: print("元素不存在") 查找元素并执行日志记录操作 python# 日志记录操作 logging.basicConfig(filename="app.log", level=logging.INFO) element = driver.find_element_by_id("com.example.app:id/element") element.click() logging.info("元素已点击") 查找元素并执行发送邮件操作 python# 发送邮件操作 with open("app.log", "r") as f: text = f.read() msg = EmailMessage() msg.set_content(text) msg["Subject"] = "App日志" msg["From"] = "[email protected]" msg["To"] = "[email protected]" with smtplib.SMTP("localhost") as smtp: smtp.send_message(msg) 查找元素并执行短信发送操作 python# 短信发送操作 client = TwilioRestClient(account_sid, auth_token) message = clienssages.create( to="+1xxxxxxxxxx", from_="+1xxxxxxxxxx", body="App已完成操作" ) print(message.sid) 查找元素并执行电话通知操作 python# 电话通知操作 client = Client(account_sid, auth_token) call = client.calls.create( to="+1xxxxxxxxxx", from_="+1xxxxxxxxxx", url="http://demo.twilio.com/docs/voice.xml" ) print(call.sid) 查找元素并执行微信通知操作 python# 微信通知操作 bot = Bot(cache_path=True) bot.file_helper.send("App已完成操作") 查找元素并执行Telegram通知操作 python# Telegram通知操作 bot = telegram.Bot(token="TOKEN") bot.send_message(chat_id="CHAT_ID", text="App已完成操作")


【本文地址】

公司简介

联系我们

今日新闻

    推荐新闻

    专题文章
      CopyRight 2018-2019 实验室设备网 版权所有