How to use cap_method method in Airtest

Best Python code snippet using Airtest

win.py

Source:win.py Github

copy

Full Screen

1# -*- coding: utf-8 -*-2import ctypes3import time4import cv25import numpy as np6import win32api7import win32con8import win32gui9import win32ui10import pywintypes11from winAuto.utils.window import GetWindowInfo12from winAuto.cap_methods import BitBlt, WindowGraphicsCapture13from pywinauto.application import Application14from pywinauto import mouse, keyboard, win32structures15from pywinauto.win32functions import SetFocus16from baseImage import Rect, Point, Size, Image17from .constant import SM_XVIRTUALSCREEN, SM_YVIRTUALSCREEN, SM_CXVIRTUALSCREEN, SM_CYVIRTUALSCREEN, SCREENSHOT_MODE18from .exceptions import WinBaseError, WinConnectError19from typing import Dict, Union, Tuple, List20class Win(object):21 def __init__(self, handle: int = None, handle_title: str = None, handle_class: str = None,22 window_border: Union[Tuple, List, None] = None, cap_method=SCREENSHOT_MODE.WindowsGraphicsCapture):23 """24 Args:25 handle: 窗口句柄26 handle_title: 窗口名27 handle_class: 窗口类名28 window_border: 是否存在带有窗口名称的顶部栏29 """30 # user32 = ctypes.windll.user3231 # user32.SetProcessDPIAware()32 if handle:33 self._hwnd = int(handle)34 elif handle_class and handle_title:35 self._hwnd = self.find_window(hwnd_class=handle_class, hwnd_title=handle_title)36 elif handle_title:37 self._hwnd = self.find_window(hwnd_title=handle_title)38 elif handle_class:39 self._hwnd = self.find_window(hwnd_class=handle_class)40 else:41 self._hwnd = None42 self._hwnd = None if self._hwnd == 0 else self._hwnd43 self.app = None44 self._app = Application()45 self._top_window = None46 self._screenshot_size = Size(0, 0)47 self._window_size = Size(win32api.GetSystemMetrics(SM_CXVIRTUALSCREEN), # 全屏幕尺寸大小48 win32api.GetSystemMetrics(SM_CYVIRTUALSCREEN))49 if self._hwnd is None:50 self._hwnd = win32gui.GetDesktopWindow()51 self._screenshot_size = self._window_size52 else:53 rect = win32gui.GetClientRect(self._hwnd)54 self._screenshot_size.width = rect[2]55 self._screenshot_size.height = rect[3]56 self._window_border = window_border or self.get_window_border() # 上,下,左,右57 self.cap_fun = None58 self.cap_method = cap_method59 if self.cap_method == SCREENSHOT_MODE.BitBlt:60 self.cap_fun = BitBlt(hwnd=self._hwnd, border=self._window_border,61 screenshot_size=self._screenshot_size)62 elif self.cap_method == SCREENSHOT_MODE.WindowsGraphicsCapture:63 self.cap_fun = WindowGraphicsCapture(hwnd=self._hwnd)64 else:65 raise ValueError('未填写cap_method参数')66 self.keyboard = keyboard67 self.mouse = mouse68 print(f'设备分辨率:{self._window_size}, 窗口所用句柄: {self._hwnd}')69 self.connect()70 def connect(self, timeout: int = 5):71 """72 Args:73 timeout: 设定超时时长74 Returns:75 None76 """77 # TODO: 检测对应句柄是否在前台78 try:79 self.app = self._app.connect(handle=self._hwnd, timeout=timeout)80 self._top_window = self.app.window(handle=self._hwnd)81 except pywintypes.error as err:82 raise WinConnectError(f"连接句柄:'{self._hwnd}'超时, error={err}")83 self.set_foreground(self._hwnd)84 def click(self, point: Union[Tuple[int, int], List, Point], duration: Union[float, int, None] = 0.01,85 button: str = 'left'):86 """87 点击连接窗口的指定位置 ps:相对坐标,以连接的句柄窗口左上角为原点88 Args:89 point: 需要点击的坐标90 duration: 延迟91 button: 左右键 left/right92 Returns:93 None94 """95 if isinstance(point, (tuple, list)):96 point = Point(x=point[0], y=point[1])97 point = self._windowpos_to_screenpos(point)98 self.mouse.press(button=button, coords=(point.x, point.y))99 time.sleep(duration)100 self.mouse.release(button=button, coords=(point.x, point.y))101 def swipe(self, point1: Union[Tuple[int, int], List, Point], point2: Union[Tuple[int, int], List, Point],102 duration: Union[float, int, None] = 0.01, steps=5):103 """104 滑动一段距离105 Args:106 point1: 起始点107 point2: 终点108 duration: 滑动结束后延迟多久抬起109 steps: 步长110 Returns:111 """112 if isinstance(point1, (tuple, list)):113 point1 = Point(x=point1[0], y=point1[1])114 if isinstance(point2, (tuple, list)):115 point2 = Point(x=point2[0], y=point2[1])116 start = self._windowpos_to_screenpos(point1)117 end = self._windowpos_to_screenpos(point2)118 interval = float(duration) / (steps + 1)119 self.mouse.press(coords=(start.x, start.y))120 time.sleep(interval)121 for i in range(1, steps):122 x = int(start.x + (end.x - start.x) * i / steps)123 y = int(start.y + (end.y - start.y) * i / steps)124 self.mouse.move(coords=(x, y))125 time.sleep(interval)126 self.mouse.move(coords=(end.x, end.y))127 self.mouse.release(coords=(end.x, end.y))128 # # -----------129 # if isinstance(point1, (tuple, list)):130 # point1 = Point(x=point1[0], y=point1[1])131 #132 # if isinstance(point1, (tuple, list)):133 # point2 = Point(x=point2[0], y=point2[1])134 #135 # start = self._windowpos_to_screenpos(point1)136 # end = self._windowpos_to_screenpos(point2)137 # interval = float(duration) / (steps + 1)138 # self.mouse.press(coords=(start.x, start.x))139 # time.sleep(interval)140 # for i in range(1, steps):141 # x = int(start.x + (end.x - start.x) * i / steps)142 # y = int(start.y + (end.y - start.y) * i / steps)143 # self.mouse.move(coords=(x, y))144 # time.sleep(interval)145 # self.mouse.move(coords=(end.x, end.y))146 # self.mouse.release(coords=(end.x, end.y))147 def keyevent(self, keycode: str):148 """149 Perform a key event150 References:151 https://pywinauto.readthedocs.io/en/latest/code/pywinauto.keyboard.html152 Args:153 keycode: key code number or name154 Returns:155 None156 """157 self.keyboard.send_keys(keycode)158 def text(self, text: str):159 """160 输入文字161 Args:162 text: 待输入的文字163 Returns:164 None165 """166 self.keyevent(text)167 def screenshot(self):168 img = Image(self.cap_fun.screenshot())169 if self.cap_method == SCREENSHOT_MODE.WindowsGraphicsCapture:170 # 上,下,左,右 self._window_border171 rect = Rect(x=self._window_border[2],172 y=self._window_border[0],173 width=self._screenshot_size.width,174 height=self._screenshot_size.height)175 return img.crop_image(rect)176 return img177 @staticmethod178 def set_foreground(handle) -> None:179 """180 将指定句柄的窗口带到前台并激活该窗口181 Returns:182 None183 """184 win32gui.SetForegroundWindow(handle)185 @property186 def rect(self) -> Rect:187 """188 获取窗口客户端区域当前所在屏幕的位置189 Returns:190 窗口的位置(以全屏左上角开始为原点的坐标)191 """192 clientRect = win32gui.GetClientRect(self._hwnd)193 point = win32gui.ScreenToClient(self._hwnd, (0, 0))194 rect = Rect(x=abs(point[0]), y=abs(point[1]), width=clientRect[2], height=clientRect[3])195 return rect196 @property197 def title(self) -> str:198 """199 获取窗口名200 Returns:201 窗口名202 """203 return self._top_window.texts()204 def kill(self) -> None:205 """206 关闭窗口207 Returns:208 None209 """210 self.app.kill()211 def _windowpos_to_screenpos(self, pos: Point):212 """213 转换相对坐标为屏幕的绝对坐标214 Args:215 pos: 需要转换的坐标216 Returns:217 Point218 """219 windowpos = self.rect.tl220 pos = pos + windowpos221 return pos222 def get_window_border(self):223 info = GetWindowInfo(self._hwnd)224 print(f'rcWindow: {info.rcWindow.left} {info.rcWindow.top} {info.rcWindow.right} {info.rcWindow.bottom}')225 print(f'rcClient: {info.rcClient.left} {info.rcClient.top} {info.rcClient.right} {info.rcClient.bottom}')226 # 上,下,左,右227 border = (abs(info.rcWindow.top - info.rcClient.top) + 1, 1, 1, 1)228 return border229 @staticmethod230 def find_window(hwnd_class: str = None, hwnd_title: str = None) -> int:231 """232 根据窗口名或窗口类名获取对应窗口句柄233 Args:234 hwnd_class: 窗口类名235 hwnd_title: 窗口名236 Returns:237 窗口句柄238 """239 return win32gui.FindWindow(hwnd_class, hwnd_title)240 @staticmethod241 def get_all_hwnd() -> Dict[int, str]:242 """243 获取所有句柄244 Returns:245 """246 hwnd_title = {}247 def _fun(hwnd, *args):248 if (win32gui.IsWindow(hwnd) and249 win32gui.IsWindowEnabled(hwnd) and250 win32gui.IsWindowVisible(hwnd)):251 hwnd_title.update({hwnd: win32gui.GetWindowText(hwnd)})252 win32gui.EnumWindows(_fun, 0)...

Full Screen

Full Screen

more_wifi.py

Source:more_wifi.py Github

copy

Full Screen

1from poco.drivers.android.uiautomation import AndroidUiautomationPoco2from airtest.core.api import *3import time4from airtest.core.android import Android5def huawei():6 # device_1 = connect_device('android://192.168.103.156:48887/339b19f1?cap_method=javacap&touch_method=adb')7 # device_1 = connect_device('android:///192.168.103.156:48887?cap_method=javacap&touch_method=adb')8 # device_1 = connect_device('android:///192.168.0.108:48887?cap_method=javacap&touch_method=adb')9 device_1 = connect_device('android:///192.168.103.253:48887?cap_method=javacap&touch_method=adb')10 # device_1 = Android('android://192.168.103.156:48887?cap_method=javacap&touch_method=adb')11 poco = AndroidUiautomationPoco(device=device_1, use_airtest_input=True, screenshot_each_action=False)12 # poco(text="今日头条极速版").click()13 # poco(name="com.ss.android.article.lite:id/adg").click()14 # poco(name="com.ss.android.article.lite:id/qp").set_text("古剑奇谭三")15 for i in range(500):16 print(i)17 time.sleep(1)18 poco.swipe([0.5,0.8],[0.5,0.2])19def vivo():20 # device_1 = connect_device('android://192.168.103.156:48887/339b19f1?cap_method=javacap&touch_method=adb')21 # device_1 = connect_device('android:///192.168.103.156:48887?cap_method=javacap&touch_method=adb')22 device_1 = connect_device('android:///192.168.0.106:48887?cap_method=javacap&touch_method=adb')23 # device_1 = Android('android://192.168.103.156:48887?cap_method=javacap&touch_method=adb')24 poco = AndroidUiautomationPoco(device=device_1, use_airtest_input=True, screenshot_each_action=False)25 # poco(text="今日头条极速版").click()26 # poco(name="com.ss.android.article.lite:id/adg").click()27 # poco(name="com.ss.android.article.lite:id/qp").set_text("古剑奇谭三")28 for i in range(500):29 print(i)30 time.sleep(1)31 poco.swipe([0.5,0.8],[0.5,0.2])32if __name__ == '__main__':33 # vivo()...

Full Screen

Full Screen

连接云手机并截图.py

Source:连接云手机并截图.py Github

copy

Full Screen

1#!/usr/bin/python2# -*- coding: utf-8 -*-3import re4import time5import cv2 as cv6from airtest.core.api import connect_device, device, shell7from airtest.core.error import AdbShellError8class Phone(object):9 def __init__(self, serial_no, cap_method='javacap', touch_method='adb'):10 self.serial_no = str(serial_no)11 self.cap_method = str(cap_method)12 self.touch_method = str(touch_method)13 # 连接设备14 device_url = 'android:///%s?cap_method=%s&touch_method=%s' % (15 self.serial_no, self.cap_method, self.touch_method)16 _device = connect_device(device_url)17 self.device = _device18 print("device connect done!")19 self._rx1 = None20 self._tx1 = None21 self._rx2 = None22 self._tx2 = None23 def shell(self, *args, **kwargs):24 result = self.device.shell(*args, **kwargs)25 return result26 def save_image(self, image, filename):27 cv.imwrite(filename, image)28 return filename29 def snapshot(self, save=False):30 image = self.device.snapshot()31 if save:32 self.save_image(image, filename=f'../dataset/image/snapshot_{str(int(time.time()))}.jpg')33 return image34if __name__ == '__main__':35 # serial_no = '139.159.250.28:8126'36 # serial_no = '139.159.250.28:8129'37 # serial_no = '139.159.250.28:8132'38 serial_no = '139.159.250.28:8135'39 phone = Phone(serial_no=serial_no)...

Full Screen

Full Screen

Automation Testing Tutorials

Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run Airtest automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful