一、前置说明
Appium 原生的swipe()方法,需要指定起始坐标点的位置,方法调用偏底层。我们可以使用get_window_size()获取窗口大小,然后按比例定义起始位置,从而实现上下左右的滑动。
二、代码实现
from appium.webdriver.webdriver import WebDriver as Remote from appium.options.android import UiAutomator2Options from libs.check import CommonChecker from libs.decorators import rerun_if_exception class WebDriver(Remote): def __init__(self, command_executor, capabilities: dict, *args, **kwargs): # solve the problem: AttributeError: NoneType' object has no attribute 'to_capabilities'. # https://stackoverflow.com/questions/77118636/attributeerror-nonetype-object-has-no-attribute-to-capabilities-getting-th options = UiAutomator2Options().load_capabilities(capabilities) super().__init__(command_executor=command_executor, options=options, *args, **kwargs) def swipe_up(self, duration=500, num=1): size = self.get_window_size() x1 = size['width'] * 0.5 y1 = size['height'] * 0.75 y2 = size['height'] * 0.25 for i in range(num): self.swipe(x1, y1, x1, y2, duration) def swipe_down(self, duration=500, num=1): size = self.get_window_size() x1 = size['width'] * 0.5 y1 = size['height'] * 0.25 y2 = size['height'] * 0.75 for i in range(num): self.swipe(x1, y1, x1, y2, duration) def swip_left(self, duration=500, num=1): size = self.get_window_size() x1 = size['width'] * 0.75 y1 = size['height'] * 0.5 x2 = size['width'] * 0.05 for i in range(num): self.swipe(x1, y1, x2, y1, duration) def swip_right(self, duration=500, num=1): size = self.get_window_size() x1 = size['width'] * 0.05 y1 = size['height'] * 0.5 x2 = size['width'] * 0.75 for i in range(num): self.swipe(x1, y1, x2, y1, duration) @rerun_if_exception() def swipe_to(self, direction, duration=500, num=1): allowed = ['up', 'down', 'left', 'right'] CommonChecker.check_item_in_list(direction, allowed, 'direction') if direction == 'up': self.swipe_up(duration, num) if direction == 'down': self.swipe_down(duration, num) if direction == 'left': self.swip_left(duration, num) if direction == 'right': self.swip_right(duration, num)
在滑动页面时,可能会遇到页面未加载完成,从而导致滑动失败的问题。因此,在swipe_to() 方法上加了一个rerun_if_exception()失败重试的装饰器,相当于加了一个自动等待页面加载完成的功能。
三、Demo验证
测试代码:
def test_swipe_to(): from driver.appium.driver import WebDriver appium_server_url = 'http://localhost:4723' capabilities = { "platformName": "Android", "automationName": "uiautomator2", "deviceName": "127.0.0.1:62001", "app": "D:\\resources\\imooc.apk", } driver = WebDriver(command_executor=appium_server_url, capabilities=capabilities) driver.swipe_to('left', num=2) driver.swipe_to('right', num=2)
成功实现了滑动的效果,控制台运行结果:
============================= test session starts ============================= collecting ... collected 1 item test_appium.py::test_swipe_to PASSED [100%] ============================= 1 passed in 22.46s ==============================