Python-atomac 基于Python的Mac应用Ui自动化库

一、概述

如标题,ATOMac是一个基于Python语言,通过Apple Accessibility API实现的Mac端应用Ui自动化控制库,下面是官方的说明:

We are pleased to introduce the first Python library to fully enable GUI testing of Mac applications via the Apple Accessibility API. This library was created out of desperation. Existing tools such as using appscript to send messages to accessibility objects are painful to write and slow to use. ATOMac has direct access to the API. It's fast and easy to use to write tests.

二、安装

  1. 由于该库pip包已经很久没更新了,直接pip安装可能会报错,Python2建议使用easy_install安装
  2. 目前atomac 1.1.0不支持Python3,但是@daveenguyen这位大神已经在源码库做了Python3的兼容,所以需要直接从git仓库安装,详细如下:
# Python2
sudo easy_install atomac

# Python3
pip3 install git+https://github.com/pyatom/pyatom/

三、使用

基础的用法在官网有说明,这里就不再赘述,以下将以地图为例,实现一些常用功能

  1. 应用的bundle_id:打开应用内容 -> info.plist

  2. Accessibility Inspector:Xcode -> Open Developer Tools


    image.png
  3. 示例代码

import atomac
from time import sleep
from atomac.AXKeyCodeConstants import *
bundle_id = 'com.apple.Maps'

# bs = atomac.AXClasses.AXKeyCodeConstants.BACKSPACE
# part 1, 启动应用并获取应用信息
atomac.launchAppByBundleId(bundle_id)
sleep(2)
ato = atomac.getAppRefByBundleId(bundle_id)
print(ato)

# part 2, 获取当前应用windows
cur_win = ato.windows()[0]
print(cur_win)

# part 3, 查找元素
# findFirst,返回第一个匹配的元素
# findFirstR,递归查找,返回第一个匹配的元素(当查找的元素Parent非标准窗口时使用)
# 在AXClasses.py文件中可以找到很多已经定义好的方法
# dt = cur_win.radioButtonsR('地图')[0]   # 也可以
dt = cur_win.findFirstR(AXRole='AXRadioButton', AXTitle='地图')
gj = cur_win.findFirstR(AXRole='AXRadioButton', AXTitle='公交')
wx = cur_win.findFirstR(AXRole='AXRadioButton', AXTitle='卫星')

# part 4, 元素属性所有
attr = dt.getAttributes()
# 元素某一个属性
dt_title = dt.AXTitle
print(attr, dt_title)

# part 5, 点击/切到公交
# Method 1,唯一定位元素后,使用Press方法
print(gj)
gj.Press()
# Method 2,定位元素坐标并鼠标点击
# 注意AXPositon得到的坐标是元素左上角的坐标,需要根据实际大小得到元素中心点坐标
dt_position = dt.AXPosition
dt_size = dt.AXSize
coord = (dt_position[0] + dt_size[0] / 2, dt_position[1] + dt_size[1])
print(coord)
dt.clickMouseButtonLeft(dt_position)

# part 6, 输入内容(输入键盘字符,US_keyboard)
s1 = cur_win.findFirstR(AXRole='AXTextField', AXRoleDescription='搜索文本栏')
# s1 == s2
# s2 = cur_win.textFieldsR('搜索文本栏')[0]
s1_p = s1.AXPosition
s1_s = s1.AXSize
s1.tripleClickMouse((s1_p[0] + s1_s[0] / 2, s1_p[1] + s1_s[1] / 2))
s1.sendKeys('7983')

# part 7, 输入键盘上的修饰符
sleep(1)
s1.sendKeys([BACKSPACE])
# 回车
s1.sendKeys([RETURN])
  1. 元素属性对应说明
    比较特殊的是:AXRoleDescription - Type
ATOMAC ACCESSIBILITY INSPECTOR
AXSize Size
AXRole Role
AXPosition Position
AXRoleDescription Type
AXValue Value
... ...

参考

https://github.com/pyatom/pyatom
https://blog.csdn.net/sinat_40766770/article/details/91048760

你可能感兴趣的:(Python-atomac 基于Python的Mac应用Ui自动化库)