airtest 进行自动化测试

🌙 airtest 进行自动化测试

🌙 环境安装

  • 1.下载 airtest: https://airtest.doc.io.netease.com/

  • 2.设置 airtest python环境为本地python环境 为安装第三方包准备

  • 3.pip安装包

pip install airtest
pip install airtest -i https://pypi.tuna.tsinghua.edu.cn/simple # 国内镜像更快

pip install pocoui

pip install pytesseract # pytesseract ocr 需结合tesseract使用
pip install wechat_ocr # wechat_ocr ocr 需结合wechat-ocr使用
1
2
3
4
5
6
7

4.安装 ocr 图片文字识别 tesseract

  • 使用tesseract软件 https://digi.bib.uni-mannheim.de/tesseract/

    中文语言包:https://github.com/tesseract-ocr/tessdata/blob/main/chi_sim.traineddata

# pytesseract ocr    
def pytesseract_ocr(img_file):
    image = Image.open(img_file)
    image = image.convert('L')
    enhancer = ImageEnhance.Contrast(image)
    image = enhancer.enhance(2)
    image = image.filter(ImageFilter.MedianFilter())
    image = image.point(lambda x: 0 if x < 140 else 255)
    txt = pytesseract.image_to_string(image, lang='chi_sim+eng')
    print(f"识别结果:{txt}")
1
2
3
4
5
6
7
8
9
10
  • wechat ocr

    https://blog.csdn.net/u013851294/article/details/144397943

    https://juejin.cn/post/7432193949765287962

def wechat_ocr_result_callback(img_path:str, results:dict):
    print(f"识别成功,{results}")
    # 获取所有的text文本
    txt = ""
    for result in results['ocrResult']:
        txt += result["text"]
    save_ocr_text(current_index, txt, img_path)
    print(f"识别结果:{txt}")

def wechat_ocr(file): 
    # wechat ocr dir C:\Users\<你的用户名>\AppData\Roaming\Tencent\WeChat\XPlugin\Plugins\WeChatOCR\..
    wechat_ocr_dir = r"C:\Users\admin\AppData\Roaming\Tencent\WeChat\XPlugin\Plugins\WeChatOCR\7079\extracted"
    # wechat install dir
    wechat_dir = r"C:\Program Files (x86)\Tencent\WeChat\[3.9.12.17]"
    
    ocr_manager = OcrManager(wechat_dir)
    # 设置WeChatOcr目录
    ocr_manager.SetExePath(wechat_ocr_dir)
    # 设置微信所在路径
    ocr_manager.SetUsrLibDir(wechat_dir)
    # 设置ocr识别结果的回调函数
    ocr_manager.SetOcrResultCallback(wechat_ocr_result_callback)
    # 启动ocr服务
    ocr_manager.StartWeChatOCR()
    # 开始识别图片
    ocr_manager.DoOCRTask(file)
    sleep(1)
    while ocr_manager.m_task_id.qsize() != OCR_MAX_TASK_ID:
        pass
    # 识别输出结果
    ocr_manager.KillWeChatOCR()
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
  1. 开启手机开发者模式

  2. adb 调试

  • 使用真机自动化测试 android app
  1. windows 本地调试
  • 使用 微信 pc端自动化测试 微信小程序
  1. 使用 mumu 模拟器自动化测试 android app

  2. 自动化 python 脚本编写

  • 读取 csv
import csv
import os

def read_csv(source_file):
    if not os.path.exists(source_file):
        print("Oops! source_file not exists")
        return []
    
    data = []  # 初始化 data 列表
    
    try:
        with open(source_file, 'r') as myFile:
            lines = csv.reader(myFile)
            for index, line in enumerate(lines):
                # 从第二行开始
                if index > 0:
                    username = str(line[0]).strip()
                    pwd = str(line[1]).strip()
                    data.append({'username': username, 'pwd': pwd})
    except Exception as e:
        print(f"An error occurred: {e}")
    
    return data  # 返回读取的数据

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
  • 保存 csv
import csv
import os

def save_csv(data, target_file):
    # 1. 检查文件是否存在
    file_exists = os.path.exists(target_file)
    
    try:
        with open(target_file, 'a', newline='') as myFile:
            writer = csv.writer(myFile)
            
            # 2. 如果文件不存在,则创建csv文件,并设置 Header
            if not file_exists:
                writer.writerow(['username', 'pwd'])
            
            # 3. 如果文件存在,则追加数据
            for item in data:
                writer.writerow([item['username'], item['pwd']])
    except Exception as e:
        print(f"An error occurred: {e}")
   
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
  • 读取 excel
import openpyxl
import os

def read_excel(source_file):
    if not os.path.exists(source_file):
        print("Oops! source_file not exists")
        return []
    
    data = []
    
    try:
        workbook = openpyxl.load_workbook(source_file)
        sheet = workbook.active
        for row in sheet.iter_rows(min_row=2, values_only=True):
            username = str(row[0]).strip()
            pwd = str(row[1]).strip()
            data.append({'username': username, 'pwd': pwd})
    except Exception as e:
        print(f"An error occurred: {e}")
    
    return data
        
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
  • 保存 excel
import os
import openpyxl
from openpyxl.drawing.image import Image

def save_excel(data, target_file):
    # 1. 检查文件是否存在
    file_exists = os.path.exists(target_file)
    
    try:
        if file_exists:
            # 如果文件存在,加载现有工作簿
            workbook = openpyxl.load_workbook(target_file)
            sheet = workbook.active
        else:
            # 如果文件不存在,创建新的工作簿和工作表
            workbook = openpyxl.Workbook()
            sheet = workbook.active
            # 设置 Header
            sheet.append(['username', 'pwd', 'image'])
        
        # 2. 追加数据
        for item in data:
            if 'username' in item and 'pwd' in item and 'img_path' in item:
                row = sheet.max_row + 1
                sheet.append([item['username'], item['pwd']])
                # 插入本地图片
                try:
                    img = Image(item['img_path'])
                    sheet.add_image(img, f'C{row}')  # 在 C 列插入图片
                except Exception as img_error:
                    print(f"Error inserting image: {img_error}")
            else:
                print(f"Invalid data item: {item}")
        
        # 保存工作簿
        workbook.save(target_file)
    except Exception as e:
        print(f"An error occurred: {e}")
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38

注意:

  1. airtest 应用程序必须以管理员权限运行,否则会闪退。
  2. 如果使用了第三方 python 包,则需要修改 airtest python 环境 为 本地 python 环境。