我正在参加「掘金·启航计划」
起因:为啥要自动加微信好友
例如推广一个产品电话和用户沟通有意向后,就添加用户微信号,同样的操作需要减少重复劳动
怎么做
- 我用苹果电脑,从mac开始做 想到用自动化测试的方式
- 搜索一下atomac可以用
- 思路确定了,读取文件里的待添加列表,然后用atomac驱动微信,逐个发送添加请求
开始
- 先了解一下atomac
是一个 Python 库,可以通过 Apple Accessibility API 完全启用 Mac 应用程序的 GUI 测试。 它可以快速且易于使用来编写测试。使用过程中可以用Accessibility Inspector工具查看应用的结构,再根据结构进行编码
- 安装atomac
# Python3
pip3 install git+https://github.com/pyatom/pyatom/
- 建立建立一个Demo工程,先验证atomac的可用性
- 注意atomac控制Mac需要提前在安全性和隐私里隐私里面辅助功能添加到允许控制列表
import atomac
bundle_id = 'com.tencent.xinWeChat'
atomac.launchAppByBundleId(bundle_id)
ato = atomac.getAppRefByBundleId(bundle_id)
- 经过不断的摸索,看文档,打日志,再结合Accessibility Inspector工具查看应用的结构,初步脚本如下,核心功能可以实现
import atomac
import time
from atomac.AXKeyCodeConstants import *
def clickCenter( item ):
"点击按钮中心点"
item_position = item.AXPosition
item_size = item.AXSize
item_coord = (item_position[0] + item_size[0] / 2, item_position[1] + item_size[1]/2)
item.clickMouseButtonLeft(item_coord)
return
bundle_id = 'com.tencent.xinWeChat'
# 启动mac上的微信
atomac.launchAppByBundleId(bundle_id)
# 获取应用
ato = atomac.getAppRefByBundleId(bundle_id)
# windows会变化,用的时候需要再取
awin = ato.windows()[0]
# 朋友圈
# dt = awin.buttons()[4]
# 通讯录 点击切换到通讯录tab
contact_btn = awin.radioButtons()[1]
clickCenter(contact_btn)
time.sleep(1)
# 添加朋友按钮
sg = awin.findFirst(AXRole='AXSplitGroup')
add_btn = sg.buttons()[0]
clickCenter(add_btn)
time.sleep(1)
input_item = sg.findFirst(AXRole='AXTextField')
input_item.sendKeys('')
# 需要添加的微信号或者手机号
input_item.sendKeys('xxxxxx')
input_item.sendKeys([RETURN])
# 等搜索结果弹窗
time.sleep(1)
# 再次获取window
awin0 = ato.windows()[0]
arow = awin0.findFirstR(AXRole='AXStaticText')
clickCenter(arow)
#等好友信息弹窗
time.sleep(1)
# 弹窗里的添加按钮
add_btn = ato.windows()[0].findAllR()[3]
clickCenter(add_btn)
# 这时已经弹出发送好友请求的弹窗
print(ato.findAllR())
- TODO,添加读取文件,异常处理等逻辑 增强健壮性
总结
功能还没实现完整,行百里者半九十,后面还有好多要做的,通过这个需求练习了mac应用自动化测试,掌握了atomac 和 Accessibility Inspector 的用法。当然条条大路通罗马肯定还有更好的方法,欢迎讨论👏