uiautomator2+python进行手机自动化

安装:

pip install --upgrade --pre uiautomator2

初始化(连接手机):

python -m uiautomator2 init
python -m uiautomator2 init --mirror

监控手机:

  • 安装:pip install --pre -U weditor
  • 打开:python -m weditor
  • 创建快捷方式(windows):python -m weditor --shortcut

使用usb:

adb forward tcp:7912 tcp:7912

使用wifi連接:

adb tcpip 5555
查看手機IP地址為:192.168.1.95
adb connect 192.168.1.95:5555

定位:

text, textContains, textMatches, textStartsWith
className, classNameMatches
description, descriptionContains, descriptionMatches, descriptionStartsWith
checkable, checked, clickable, longClickable
scrollable, enabled,focusable, focused, selected
packageName, packageNameMatches
resourceId, resourceIdMatches
index, instance

初始化:

import time
import uiautomator2 as u2
import uiautomator2.ext.htmlreport as htmlreport

d = u2.connect('232e730f') #adb devices
print(d.device_info)
report = htmlreport.HTMLReport(d)
report.patch_click()
d.app_start("cisystem.ptah.mobile")
time.sleep(15)
d.app_stop('cisystem.ptah.mobile') #不会清空数据
# d.app_clear('cisystem.ptah.mobile') #会清空数据

日期选择:

对手机上日期控件不能通过send_keys方法写入日期时,通过一个个元素点击进行的日期选择

 def selectDate(self,ele, toDate):
        self.d(description=ele).click()
        date = toDate.split(" ")
        day = date[0]
        month = date[1][:-1]
        year = date[2]
        if self.d(resourceId="android:id/date_picker_header_year").get_text() != year:
            # 選擇年份
            self.d(resourceId="android:id/date_picker_header_year").click()
            # 點擊確定
            self.d(text=year).click()
        # 計算時間與默認時間相差x
        dateDesc = self.d(text="1").info.get("contentDescription")
        currentMonth = dateDesc.split(" ")[1][:-1]
        x = int(month) - int(currentMonth)
        # 正數點擊下一頁x下,負數點擊上一頁x下
        if x > 0:
            for i in range(x):
                self.d(resourceId="android:id/next").click()
        else:
            for i in range(abs(x)):
                self.d(resourceId="android:id/prev").click()
        # 找到對應xpath的元素
        self.d(description=toDate).click()
        self.d(text="確定").click()

参考:

  • https://github.com/openatx/uiautomator2

你可能感兴趣的:(Appium,uiautomator2)