用Python+哪个操作APP库,并可以APP适合做接口自动化吗在后台点击运行

Python实现浏览器自动化操作
最近在研究网站自动登录的问题,涉及到需要实现浏览器自动化操作,网上有不少介绍,例如使用pamie,但是只是支持IE,而且项目也较久没有更新了。还有就是利用selenium,可支持多种浏览器。网上资料比较多。经过比较,我选择了Splinter模块,因为利用Splinter开发浏览器自动化操作,编写代码比较简单。
一、Splinter的安装
Splinter的使用必修依靠Cython、lxml、selenium这三个软件。所以,安装前请提前安装
Cython、lxml、selenium。以下给出链接地址:
1)http://download.csdn.net/detail/feisan/4301293
2)http://code.google.com/p/pythonxy/wiki/AdditionalPlugins#Installation_no
3)http://pypi.python.org/pypi/selenium/2.25.0#downloads
4)http://splinter.cobrateam.info/
二、Splinter的使用
这里,我给出自动登录126邮箱的案例。难点是要找到页面的账户、密码、登录的页面元素,这里需要查看126邮箱登录页面的源码,才能找到相关控件的id.
例如:输入密码,密码的文本控件id是pwdInput.可以使用browser.find_by_id()方法定位到密码的文本框,
接着使用fill()方法,填写密码。至于模拟点击按钮,也是要先找到按钮控件的id,然后使用click()方法。
由于代码较简单,我就只在代码中给出注解说明工作原理。
(测试环境win7+python2.7.3+firefox)
1)登录截图
----------------------------------------
#coding=utf-8
import time
from splinter import Browser
def splinter(url):
&&& browser =
&&& #login 126
email websize
browser.visit(url)
&&& #wait web
element loading
time.sleep(5)
&&& #fill in
account and password
browser.find_by_id('idInput').fill('xxxxxx')
browser.find_by_id('pwdInput').fill('xxxxx')
&&& #click the
button of login
browser.find_by_id('loginBtn').click()
time.sleep(8)
&&& #close the
window of brower
browser.quit()
if __name__ == '__main__':
&&& websize3
='http://www.126.com'
splinter(websize3)
-------------------------------------------
已投稿到:
以上网友发言只代表其个人观点,不代表新浪网的观点或立场。阅读(2291)
1.1 编制目的
该文档为选用Appium作为移动设备原生(Native)、混合(Hybrid)、移动Web(Mobile Web)应用UI自动化测试的相关自动化测试人员、开发人员等提供参考。
1.2 预期读者
自动化测试人员、测试代表、开发人员等。
2.1 Appium设计哲学
不需要为了自动化而且重新编译或修改测试app;
不应该让移动端自动化测试限定在某种语言和某个具体的框架;也就是说任何人都可以使用自己最熟悉最顺手的语言以及框架来做移动端自动化测试;
不要为了移动端的自动化测试而重新发明轮子,重新写一套惊天动地的api;也就是说webdriver协议里的api已经够好了,拿来改进一下就可以了;
移动端自动化测试应该是开源的;
2.2 Appium技术框架(C/S 框架)
Appium的核心是一个暴露了一系列REST API的Server。这个server的主要功能:监听一个端口,然后接收由client发送来的命令(command)。解析这些command,把这些command转成移动设备可以理解的形式发送给移动设备,然后移动设备执行完这些command后把执行结果返回给server, server再把执行结果返回给client。
client就是发起command的设备,一般来说就是我们代码执行的机器,执行appium测试代码的机器。狭义点理解,可以把client理解成是代码,这些代码可以是java/ruby/python/js的,只要它实现了webdriver标准协议就可以。
这样的设计思想带来了一些好处:
1)多语言的支持;
2)可把server放在任意机器上,支持云测试;
图1 Appium架构
图2 Appium Android模型
图3 AppiumiOS模型
2.3 Appium Server/Client
Appium Server即服务器,连接Appium客户端和移动设备。原生的webdriverapi为web端设计,因此扩展到移动端要拓展。Appium官方提供了一套appium client,涵盖多种语言ruby/java/python等。
2.4 会话Session
在webdriver/appium,所有测试都必须在Appium Server和移动设备之间创建会话(Session)后才可以进行。一般来说,通过POST/session这个URL,然后传入会话属性(Desired Capabilities)就可以开启会话了。开启会话后,会返回一个全局唯一的会话ID(session id),之后几乎所有的请求都基于该会话ID,该会话ID代表了你所打开的浏览器或者是移动设备的模拟器,连接执行机器和移动设备。由于每个移动设备的连接会话ID是全局唯一的,那么在同一台机器上启动多个会话就变成了可能,这使多移动设备的并发测试成为可能。
会话属性(Desired Capabilities)包含会话配置信息,以key-value形式存在,可以理解成是java里的map,python里的字典,ruby里的hash以及javascript里的json对象(实际上,Appium Server和移动设备之间的会话属性就是通过json对象传输)
3 Appium安装
Appium Windows版仅支持Android设备(手机),Appium Mac版同时支持Android和iOS设备(手机)。
3.1 Windows版安装(64位)
3.1.1 软件列表
1)JDK& 1.6
2)vcredist_x86_c++
3).Net Framework & 4.0
3)(ADT-Bundle-windows-x86-64)
4)Appium for windows(最新版1.4.16.1)
5) Appium client(根据使用的语言安装一种即可:Java/Python/Ruby等),对于Java客户端,还需要Selenium包selenium-java-2.46.0.jar , selenium-server-standalone-2.46.0.jar,python的是Appium-python-client(就是一个python类库)
6)Android手机驱动(for windows),windows必须安装任意一个Android手机驱动,否则,adb无法检测无设备。
3.1.2 安装过程
按照JDK、vcredist_x86_c++、.NET Framework、Appium的顺序安装好各软件,ADT直接下载就可以用无需安装
1)JDK安装:设置系统环境变量JAVA_HOME为JDK安装路径:(Java安装和环境变量配置,自行百度)
2)vcredist_x86_c++安装:百度下载vcredist_x86_c++.exe文件,双击安装即可。
3).NET Framework安装:百度一个大于4.0版本的.NET Framework.exe文件。双击安装即可。
4)Appium服务端安装:下一个Appium for windows 1.4.16版本,双击安装即可。(注:Appium分为客服端和服务端,服务端就是Appium工具,又可以分为GUI版本和终端版本。GUI版本是可视化的图像界面工具,终端版本是在终端启动的一个服务而已。客服端就是针对python、java、ruby等语言开发的类库)
5)ADB安装:ADB是ADT的一个工具,所以,在要下一个ADT的安装包(免安装的)解压即可。然后,设置系统环境变量ANDROID_HOME为ADT所在目录(比如D:\Mobile-AutoTest-Software\adt-bundle-windows-x86_64-\sdk),同时把并把ADT里的tools和platform-tools两个目录加入到系统的&Path路径里:注意:adb需要安装adb驱动,一般手机驱动自带adb驱动,所以只要安装一个手机驱动即可
& & & & & & & & && & & & & & & & & & & & & & & & &&
adb安装成功后在终端输入adb devices会弹出PC端连接的设备的udid
&                    
6)python安装:下一个python2.7的安装包,双击安装即可。如果需要通过python安装相关的python类库,还要安装pypa-setuptools、pip等工具。
6)Appium客服端安装:安装Appium Client(客户端只需安装一个,比如Python的或者Java的)这里以python为例:
1、需首先安装Python、pypa-setuptools、pip等Python环境(安装过程自行百度),然后通过pip在线(PC需联网)安装Selenium及Python客户端(cmd下切换到Python安装目录C:\Python27\Lib\site-packages\后执行):
python pip install Selenium
python pip install Appium-Python-Client
2、设置环境变量,把Python的目录加到系统的Path路径里
安装Appium-Python-Client客户端时有时会遇到setuptools版本问题,运行python pip install –upgrade setuptools升级后再安装:
   &                
如果机器没联网,下载Selenium和Appium-Python-Client,并解压把整个目录放到Python安装目录(一般是C:\Python27\Lib\site-packages 目录下),如下图(selenium-2.53.1目录下py目录的selenium目录拷贝到上面的site-packages目录)
&&&&&&                    
Java客户端可直接下载Jar包(比如java-client-3.2.0.jar),在Java工程中添加Jar即可。
其他客户端安装【略】&
按照如上步骤安装好各软件后,基本环境就算完成了。启动Appum,填写被测APP路径,Platform选Android,Automation Name选Appium,PlatformVersion根据手机的Android版本选择,DeviceName选择上面adb命令识别的手机udid号;Server地址和端口保持默认:
配置上面两项内容后,点击启动按钮,看到最后一行信息及表示启动成功:
3.2 Mac版安装
3.2.1 软件列表
Mac Pro (OS X 10.10.3)
Appium for Mac(最新版Appium-1.4.13.dmg)
Appium Client(Python、Java等),对于Java客户端,还需要Selenium包selenium-java-2.46.0.jar , selenium& -server-standalone-2.46.0.jar
3.2.2 Appium安装过程
安装brew&:终端输入ruby –e "$(curl –fsSL)"
安装node.js:到官网下载Mac的pkg安装包,下载完成直接安装即可无需配置任何参数。在终端输入node –version 如有版本号出来这说明成功。(也可以通过brew、来安装:brew install node)
获取权限:sudo chmod –R& 777 /usr/local/
安装ideviceinstaller:brew update &,brew install ideviceinstaller
安装Appium服务端:npm install –g ,npm install wd(还有问题就看这篇文章:)
安装pip:sudo easy_install pip就行。
安装appium python client和selenium(客服端):pip install Appium-Python-Client,pip install selenium
过程和Windows基本一致,JDK安装过程自行百度,python咋Mac和Linux环境下是自带的无须安装。环境变量JAVE_HOME和ANDROID_HOME设置,并把ADT里的platform-tools和tools加到系统目录:
最后,启动Appium-doctor检查环境配置,全部打勾说明环境搭建完毕:
3.2.3 针对iOS10升级appium到1.6.3解决方案
由于iOS10放弃了uiautomator,改用XCUITest来进行测试。appium1.6.0之前的版本全部采用uiautomator来进行自动化测试,基于这次iOS的调整,appium1.6.0之后的版本添加了WebDriverAgent依赖来应对这次iOS的调整。这里,我针对appium1.6.3的升级过程做描述。
安装carthage,brew install carthage
安装xcpretty,gem install xcpretty
在安装好appium旧版情况下,卸载appium。npm uninstall –g& appium.
安装appium1.6.3,npm install –g appium。(这个过程会很难成功,但是,我们能做的就是不停尝试,直到安装成功为止。)
安装WebDriverAgent,cd /usr/local/lib/node_modules/appium/node_modules/appium-xcuitest-driver/WebDriverAgent(如果不在此目录,自行查找)
mkdir –p Resources/WebDriverAgent.bundle&
sh ./Scripts/bootstrap.sh –d(这步可能会报错,去下一个vpn,开启服务,再次下载就ok了,这里推荐“star vpn”很不错的vpn)
cd /usr/local/lib/node_modules/appium/node_modules/appium-xcuitest-driver/WebDriverAgent用xcode打开WebDriverAgent.xcodeproj。修改项目的Bundle identifier.要包Bundle identifier的Facebook改成其他东西。Signing,要选Automatically manage signing,开发者选自己的账号或者用证书进行编译,项目的所有bundle identifier都要该。改完后, build。
关闭xcode,在终端cd /usr/local/lib/node_modules/appium/node_modules/appium-xcuitest-driver/WebDriverAgent。
xcodebuild –project WebDriverAgent.xcodeproj –scheme WebDriverAgentRunner –destination 'id=真机的udid' test.
如果运行结果报错为“Test target WebDriverAgentRunnerencounted an error (Early unexpected exit,operationnever finished bootstrapping –no restart will be attempted)”则忽略不计。
到此升级工作完成,注意:在安装WebDriverAgent到手机的时候必须保持手机连接外网。当然,在使用的过程中同样要连接外网。(如果WedDriverAgent是用证书进行编译的则在使用过程中不用连接外网)
由于,appium1.6.3为推出GUI版本,这里做元素定位的时候,我们用macaca进行定位,macaca安装教程网上查询。
app-inspector是macaca的元素定位工具,使用命令,在终端输入:app-inspector –u "设备的udid"
3.3 Linux版安装
3.3.1 软件列表
Linux Ubuntu Destop 14.04以上版本
Android sdk
Python Appium客户端:Appium-Python-Client、Selenium
3.3.2 安装过程
Appium Server 的安装
1. 删除nodejs : &sudo apt-get remove nodejs。但是默认的系统nodejs没有,这一步可做可不做。
2. 安装ruby:sudo apt-get install ruby
确认ruby 安装成功:
ruby -v有ruby的版本信息。
3. 安装git:sudo apt-get install git
4. 安装brew:ruby -e "$(wget -O- https://raw.github.com/Homebrew/linuxbrew/go/install)"
如果上面执行不成功的话可以用下面这句git clone
~/.linuxbrew
5. 安装curl:sudo apt-get install curl
6. 安装node.js:一定不能用sudo,直接普通用户安装(确认之前文件环境配置好后,如果安装下载失败多试几次)
brew install node
如果上面执行不成功的话就用这种方法:sudo apt-get install g++。
& & & & & & & & & & & & & & & & & & & & & & & & & sudo apt-get install libssl-dev。
& & & & & & & & & & & & & & & & & & & & & & & & & wget&。
& & & & & & & & & & & & & & & & & & & & & & & & & tar zxvf node-v5.6.0.tar.gz。
& & & & & & & & & & & & & & & & & & & & & & & & & ./configure(注:这句话要切到node的bin目录下执行)。
& & & & & & & & & & & & & & & & & & & & & & & & & make。
&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& &&&&&&&&     &make install。
& & & & & & & & & & & & & & & & & & & & & & & & & sudonpm install –g express-generator@4(全局模式安装)。
可能会比较慢(本机安装15分钟左右),耐心等待nodejs安装成功。
查看安装完成
7. 安装 Java 虚拟机
下载JDK,下载最新Java SDK
我们把JDK安装到这个路径:/usr/lib/jvm
如果没有这个目录(第一次当然没有),我们就新建一个目录
1)cd /usr/lib
2)sudo mkdir jvm
建立好了以后,我们来到刚才下载好的压缩包的目录,解压到我们刚才新建的文件夹里面去,并且修改好名字方便我们管理,(根据版本名自己修改名字)
1)sudo tar zxvf ./jdk-7-linux-i586.tar.gz& -C /usr/lib/jvm
2)cd /usr/lib/jvm
3) sudo mv jdk1.7.0_05/ jdk7
配置JAVA环境变量
gedit ~/.bashrc
在打开的文件的末尾添加
export JAVA_HOME=/usr/lib/jvm/jdk7
export JRE_HOME=${JAVA_HOME}/jre
export CLASSPATH=.:${JAVA_HOME}/lib:${JRE_HOME}/lib
export PATH=${JAVA_HOME}/bin:$PATH
保存退出,然后输入下面的命令来使之生效
source ~/.bashrc
配置默认JDK
由于一些Linux的发行版中已经存在默认的JDK,如OpenJDK等。所以为了使得我们刚才安装好的JDK版本能成为默认的JDK版本,我们还要进行下面的配置。
执行下面的命令:
sudo update-alternatives --install /usr/bin/java java /usr/lib/jvm/jdk7/bin/java 300
sudo update-alternatives --install /usr/bin/javacjavac /usr/lib/jvm/jdk7/bin/javac 300
注意:如果以上两个命令出现找不到路径问题,只要重启一下计算机在重复上面两行代码就OK了。
执行下面的代码可以看到当前各种JDK版本和配置:
sudo update-alternatives --config java
打开一个终端,输入下面命令:
java -version
显示结果(JDK1.8):
java version "1.8.0_05"
Java(TM) SE Runtime Environment (build 1.8.0_05-b05)
Java HotSpot(TM) Server VM (build 23.1-b03, mixed mode)
这表示java命令已经可以运行了。
8. 安装appium
全局安装appium,本机安装的是1.4.16版本(如果不加版本名会自动安装最新版本),通过npm淘宝镜像
通过config命令
npm config set registry https://registry.npm.taobao.org (这里是为下面一句服务的,即把appium的下载数据源指向淘宝库)
npm install -g
如果安装失败就用root账号进行安装?安装完之后,
cd /usr/local/lib
sudo chown –R& 主机名字 node_modules
然后卸载:
npm uninstall appium –g
之后再普通用户下启动appium
可能会比较慢,耐心等待安装成功,如果安装失败重复执行安装命令(如果之前有安装过错误的版本,提示得删除之前的文件,删除之后在安装)。
安装成功会出现树状依赖关系图
9. 下载安装Android SDK Starter Package
Android SDK Starter Package这个只是SDK的核心基本工具,有了它,再利用它的管理工具下载其他你需要到部分。看到这个目录中有个android脚本文件了吗?执行它,就会启动Android SDK and AVD Manager,这个工具可以帮你下载其他你需要的部分,还可以创建模拟机。
下载地址是:http://developer.android.com/sdk/index.html,不过国内这个地址被墙掉了,你要想版本下载包了。
一般是下载最新版,我下载的:android-sdk_r21.1-linux.tgz。
wget http://dl.gmirror.org/android/android-sdk_r24.4.1-linux.tgz
接下来当然是解包了:tar zvxf android-sdk_r21.1-linux.tgz
解包完毕,就会在当前目录下出现android-sdk-linux_x86目录了。这个目录下就是sdk的基本工具了。记住这个目录,因为以后你运行工具或者设置ADT的时候,会需要这个目录的!。
注意,需要安装ia32-libs
sudo apt-get install -y libc6-i386 lib32stdc++6 lib32gcc1 lib32ncurses5 lib32z1&
配置 Android SDK
配置 Android 环境变量,将下面的变量添加到环境变量当中去(根据自己sdk存放的文件夹修改路径,注意HOME就为当前用户目录下)
export ANDROID_HOME="$HOME/adt/sdk"
export PATH=${PATH}:~/adt/sdk/tools
export PATH=${PATH}:~/adt/sdk/platform-tools
然后source
source ~/.bashrc
10.&安装Appium客户端(ubuntu系统自带python2.7和python3.4版本)
安装Appium-Python-Client(使用pip安装)
sudo apt-get install python-pip
sudo pip install Appium-Python-Client
(可能会失败,多试几次)
安装 selenium 2.0(/usr/local/lib/python2.7/dist-packages下也有就无需安装)
sudo apt-get install selenium
测试Appium
测试appium环境安装正确与否
appium-doctor
所有环境都打钩为正确配置好环境,查看上面的JAVA_HOME和ANDROID_HOME环境配置是否正确
命令行敲入appium
出现 welcome to appium v1.4.16 代表安装成功
将项目放到/python2.7/dist-packages文件夹下测试运行
完成!!!
4.1 控件识别(Windows)
启动Appium后,用Appium Inspector进行控件识别(如下图),可以进行点击和输入操作(Tap、Text),右边的界面会根据操作实时更新,方便连续识别控件。
4.2 控件识别(Mac)
启动Appium后,用Appium Inspector进行控件识别(如下图)。
Appium终端版本启动命令:
Linux下启动命令:appium -a 127.0.0.1 -p 端口号 -bp 端口号 --session-override --no-reset
Mac下启动命令:appium -a 127.0.0.1 -p 端口号 -bp 端口号 --session-override --no-reset --tmp 绝对路径
Mac下启动多个appium(小于1.6.0的版本)会有冲突,所以必须要对每个appium自定一个不同的数据缓存目录。因此,tmp后面的参数不能相同。appium(大于1.6.0)由于引进了WebDriverAgent,同时运行个appium客户端会导致wda的pc端端口重复,可以在测试脚本中指定setCapability("wdaLocalPort","端口一"),确保每个appium客户端wdaLocalPort端口不同。
Appium长时间运行报错:FATAL ERROR:CALL_AND_RETRY_LAST Allocation failed – process out of memory 已放弃(核心已转储)。判断为node内存溢出。这是node的bug。
5.0 python脚本实例
&driver对象类
from appium import webdriver
import time
from selenium.common.exceptions import NoSuchElementException
class driverObject:
def __init__(self, host, port, platform, version, deviceName, noReset, unicodeK, resetK, appPath ,appP_bdId, appA_udid, localPort):
#__appP_bdId = "com.yitong.fjnx.mbank.android"
__appP_bdId = appP_bdId
#__appA_udid = ".Splash"
__appA_udid = appA_udid
self.pwmode = 'lower'
self.model='Appium'
self.desired_caps = {}
self.desired_caps['platformName'] = platform
self.desired_caps['platformVersion'] = version
self.desired_caps['noReset'] = noReset
self.desired_caps['unicodeKeyboard'] = unicodeK
self.desired_caps['resetKeyboard'] = resetK
self.desired_caps['app'] = appPath
self.desired_caps['udid'] = deviceName
self.desired_caps['deviceName'] = deviceName # Android - ignored, iOS - iPhone name
if platform == "Android":
self.desired_caps['appPackage'] = __appP_bdId
self.desired_caps['appActivity'] = __appA_udid
if platform == "iOS":
self.desired_caps['bundleId'] = __appP_bdId
self.desired_caps['automationName'] = 'XCUITest'
self.desired_caps['wdaLocalPort'] = localPort
url = "http://" + host + ":" + str(port) + "/wd/hub"
self.driver = webdriver.Remote(url, self.desired_caps)
time.sleep(5)
def get_driver(self):
return self.driver
def quit(self):
self.driver.quit()
from testClass import driverObjectif __name__ == '__main__':
driver =driverObject(参数...)
脚本内容代码...
driver.quit()
&原文链接:
阅读排行榜热门搜索:
关注软件产品网
办公、管理
软件开发、网站建设
网管、安全
图形图像、多媒体
工具软件、游戏娱乐
需求发布说明:
您现在的位置: >
> 可以完成 Android UI 自动化的 Python 库
可以完成 Android UI 自动化的 Python 库
uiautomator2Android Uiautomator2 Python Wrapper 这是一个可以完成Android的UI自动化的python库。 该项目还在火热的开发中google提供的uiautomator库功能做起安卓自动化来非常强大,唯独有两个缺点:1. 只能在手机上运行 2. 只能使用java语言。 所以为了能更简单快捷的使用uiautomator,这个项目通过在手机上运行了一个http服务的方法,将uiautomator中的函数开放了出来。然后再将这些http接口,封装成了python库。这里要非常感谢 Xiaocong He ( @xiaocong ),他将这个想法实现了出来,uiautomator2这个项目则是对原有xiaocong的项目 uiautomator 进行了bug的修改,功能进行了加强。具体有以下修复uiautomator经常性退出的问题代码进行了重构和精简,方便维护增加了脱离数据线运行测试的功能通过 minicap 加快截图速度虽然我说的很简单,但是实现起来用到了很多的技术和技巧,功能非常强,唯独文档有点少。哈哈InstallationInstall python library# Since uiautomator2 is still developing, you have to add --pre to install development versionpip install --pre uiautomator2# Or you can install from sourcegit clone https://github.com/openatx/uiautomator2pip install -e uiautomator2Optional, used in screenshot()pip install pillowPush and install (apk, atx-agent, minicap, minitouch) to device电脑连接上一个手机或多个手机, 确保adb已经添加到环境变量中,执行下面的命令会自动安装 uiautomator-apk 以及 atx-agentpython -m uiautomator2 init安装提示 success 即可Usage 使用指南下文中我们用 device_ip 这个变量来定义手机的IP,通常来说安装完 atx-agent 的时候会自动提示你手机的IP是多少。如果手机的WIFI跟电脑不是一个网段的,需要先通过数据线将手机连接到电脑上,使用命令 adb forward tcp:7912 tcp:7912 将手机上的服务端口7912转发到PC上。这个时候连接地址使用 127.0.0.1 即可。命令行使用init: 初始化设备的atx-agent等Installation部分已经介绍过,这里就不写了install: 通过URL安装应用$ python -m uiautomator2 install $device_ip https://example.org/some.apkMainThread: 15:37:55,731 downloading 80.4 kB / 770.6 kBMainThread: 15:37:56,763 installing 770.6 kB / 770.6 kBMainThread: 15:37:58,780 success installed 770.6 kB / 770.6 kBclear-cache: 清空缓存$ python -m uiautomator2 clear-cacheapp-stop-all : 停止所有应用$ python -m uiautomator2 app-stop-all $device_ipQUICK STARTOpen python, input with the following codeThere are two ways to connect to the device.Through WIFI (recommend) Suppose device IP is 10.0.0.1 and your PC is in the same network.import uiautomator2 as u2d = u2.connect('10.0.0.1') # same as call with u2.connect_wifi('10.0.0.1')print(d.info)Through USB Suppose device serial is 123456fimport uiautomator2 as u2d = u2.connect('123456f') # same as call with u2.connect_usb('123456f')print(d.info)If just call u2.connect() with no arguments, env-var ANDROID_DEVICE_IP will first check. if env-var is empty, connect_usb will be called. you need to make sure there is only one device connected with your computer.一些常用但是不知道归到什么类里的函数先中文写着了,国外大佬们先用Google Translate顶着检查并维持uiautomator处于运行状态d.healthcheck()连接本地的设备需要设备曾经使用 python -muiautomator2 init 初始化过d = u2.connect_usb(&{Your-Device-Serial}&)一定时间内,出现则点击10s内如果出现Skip则点击clicked = d(text='Skip').click_exists(timeout=10.0)打开调试开关用于开发者或有经验的使用者定位问题&&& d.debug = True&&& d.info12:32:47.182 $ curl -X POST -d '{&jsonrpc&: &2.0&, &id&: &b80d3af3e9cb3e&, &method&: &deviceInfo&, &params&: {}}' 'http://127.0.0.1:54179/jsonrpc/0'12:32:47.225 Response &&&{&jsonrpc&:&2.0&,&id&:&b80d3af3e9cb3e&,&result&:{&currentPackageName&:&com.android.mms&,&displayHeight&:1920,&displayRotation&:0,&displaySizeDpX&:360,&displaySizeDpY&:640,&displayWidth&:1080,&productName&:&odin&,&screenOn&:true,&sdkInt&:25,&naturalOrientation&:true}}&&& ENDNotes:In below examples, we use d represent the uiautomator2 connect objectTable of ContentsRetrive the device infoKey Event Actions of the deviceGesture interaction of the deviceScreen Actions of the deviceChild and sibling UI objectGet the selected ui object status and its informationPerform the click action on the seleted ui objectGesture action for the specific ui objectTODOBasic API UsagesThis part show the normal actions of the device through some simple examplesRetrive the device infod.infoBelow is a possible result:{&& & u'displayRotation': 0,& & u'displaySizeDpY': 640,& & u'displaySizeDpX': 360,& & u'currentPackageName': u'com.android.launcher',& & u'productName': u'takju',& & u'displayWidth': 720,& & u'sdkInt': 18,& & u'displayHeight': 1184,& & u'naturalOrientation': True}Key Event Actions of the deviceTun on/off screend.screen_on() # turn on screend.screen_off() # turn off screenGet screen on/off statusd.info.get('screenOn') # require android &= 4.4Press hard/soft keyd.press(&home&) # press home keyd.press(&back&) # the normal way to press back keyd.press(0x07, 0x02) # press keycode 0x07('0') with META ALT(0x02)Next keys are currently supported:homebackleftrightupdowncentermenusearchenterdelete ( or del)recent (recent apps)volume_upvolume_downvolume_mutecamerapowerYou can find all key code definitions at Android KeyEvnetUnlock screend.unlock()# 1. launch activity: com.github.uiautomator.ACTION_IDENTIFY# 2. press &home&Gesture interaction of the deviceClick the screend.click(x, y)Long click the screend.long_click(x, y)d.long_click(x, y, 0.5) # long click 0.5s (default)Swiped.swipe(sx, sy, ex, ey)d.swipe(sx, sy, ex, ey, 0.5) # swipe for 0.5s(default)Dragd.drag(sx, sy, ex, ey)d.drag(sx, sy, ex, ey, 0.5) # swipe for 0.5s(default)Note: click, swipe, drag support percent position. Example:d.long_click(0.5, 0.5) means long click center of screenScreen Actions of the deviceRetrieve/Set OrientationThe possible orientation is:natural or nleft or lright or rupsidedown or u (can not be set)# retrieve orientation, it may be &natural& or &left& or &right& or &upsidedown&orientation = d.orientation# WARNING: not pass testing in my TT-M1# set orientation and freeze rotation.# notes: &upsidedown& can not be set until Android 4.3.d.set_orientation('l') # or &left&d.set_orientation(&l&) # or &left&d.set_orientation(&r&) # or &right&d.set_orientation(&n&) # or &natural&Freeze/Un-Freeze rotation# freeze rotationd.freeze_rotation()# un-freeze rotationd.freeze_rotation(False)Take screenshot# take screenshot and save to local file &home.jpg&, can not work until Android 4.2.d.screenshot(&home.jpg&)# get PIL.Image format, need install pillow firstimage = d.screenshot()image.save(&home.jpg&) # or home.png# get opencv format, need install numpy and cv2import cv2image = d.screenshot(format='opencv')cv2.imwrite('home.jpg', image)Dump Window Hierarchy# or get the dumped content(unicode) from return.xml = d.dump_hierarchy()Open notification or quick settingsd.open_notification()d.open_quick_settings()Push and pull filepush file into device# push into a folderd.push(&foo.txt&, &/sdcard/&)# push and renamed.push(&foo.txt&, &/sdcard/bar.txt&)# push fileobjwith open(&foo.txt&, 'rb') as f:& & d.push(f, &/sdcard/&)# push and change file moded.push(&foo.sh&, &/data/local/tmp/&, mode=0o755)pull file from deviced.pull(&/sdcard/tmp.txt&, &tmp.txt&)# FileNotFoundError will raise if file not found in deviced.pull(&/sdcard/some-file-not-exists.txt&, &tmp.txt&)App managementInclude app install, launch and stopApp installOnly support install from url for now.d.app_install('http://some-domain.com/some.apk')App launchd.app_start(&com.example.hello_world&) # start with package nameApp stop# perform am force-stopd.app_stop(&com.example.hello_world&)&# perform pm cleard.app_clear('com.example.hello_world')App stop all the runnings# stop alld.app_stop_all()# stop all app except com.examples.demod.app_stop_all(excludes=['com.examples.demo'])SelectorSelector is to identify specific ui object in current window.# To seleted the object ,text is 'Clock' and its className is 'android.widget.TextView'd(text='Clock', className='android.widget.TextView')Selector supports below parameters. Refer to UiSelector java doc for detailed information.text , textContains , textMatches , textStartsWithclassName , classNameMatchesdescription , descriptionContains , descriptionMatches , descriptionStartsWithcheckable , checked , clickable , longClickablescrollable , enabled , focusable , focused , selectedpackageName , packageNameMatchesresourceId , resourceIdMatchesindex , instanceChild and sibling UI objectchild# get the child or grandchildd(className=&android.widget.ListView&).child(text=&Bluetooth&)sibling# get sibling or child of siblingd(text=&Google&).sibling(className=&android.widget.ImageView&)child by text or description or instance# get the child match className=&android.widget.LinearLayout&# and also it or its child or grandchild contains text &Bluetooth&d(className=&android.widget.ListView&, resourceId=&android:id/list&) \&.child_by_text(&Bluetooth&, className=&android.widget.LinearLayout&)# allow scroll search to get the childd(className=&android.widget.ListView&, resourceId=&android:id/list&) \&.child_by_text(& & &Bluetooth&,& & allow_scroll_search=True,& & className=&android.widget.LinearLayout&& )child_by_description is to find child which or which's grandchild contains the specified description, others are the same as child_by_text .child_by_instance is to find child which has a child UI element anywhere within its sub hierarchy that is at the instance specified. It is performed on visible views without scrolling.See below links for detailed information:UiScrollable , getChildByDescription , getChildByText , getChildByInstanceUiCollection , getChildByDescription , getChildByText , getChildByInstanceAbove methods support chained invoking, e.g. for below hierarchy&node index=&0& text=&& resource-id=&android:id/list& class=&android.widget.ListView& ...&& &node index=&0& text=&WIRELESS & NETWORKS& resource-id=&& class=&android.widget.TextView& .../&& &node index=&1& text=&& resource-id=&& class=&android.widget.LinearLayout& ...&& & &node index=&1& text=&& resource-id=&& class=&android.widget.RelativeLayout& ...&& & & &node index=&0& text=&Wi-Fi& resource-id=&android:id/title& class=&android.widget.TextView& .../&& & &/node&& & &node index=&2& text=&ON& resource-id=&com.android.settings:id/switchWidget& class=&android.widget.Switch& .../&& &/node&& ...&/node&We want to click the switch at the right side of text 'Wi-Fi' to turn on/of Wi-Fi. As there are several switches with almost the same properties, so we can not use like d(className=&android.widget.Switch&) to select the ui object. Instead, we can use code below to select it.d(className=&android.widget.ListView&, resourceId=&android:id/list&) \& .child_by_text(&Wi-Fi&, className=&android.widget.LinearLayout&) \& .child(className=&android.widget.Switch&) \& .click()relative positionAlso we can use the relative position methods to get the view: left , right , top , bottom.d(A).left(B) , means selecting B on the left side of A.d(A).right(B) , means selecting B on the right side of A.d(A).up(B) , means selecting B above A.d(A).down(B) , means selecting B under A.So for above case, we can write code alternatively:## select &switch& on the right side of &Wi-Fi&d(text=&Wi-Fi&).right(className=&android.widget.Switch&).click()Multiple instancesSometimes the screen may contain multiple views with the same e.g. text, then you will have to use &instance& properties in selector like below:d(text=&Add new&, instance=0) &# which means the first instance with text &Add new&However, uiautomator provides list like methods to use it.# get the count of views with text &Add new& on current screend(text=&Add new&).count# same as count propertylen(d(text=&Add new&))# get the instance via indexd(text=&Add new&)[0]d(text=&Add new&)[1]...# iteratorfor view in d(text=&Add new&):& & view.info &# ...Notes: when you are using selector like a list, you must make sure the screen keep unchanged, else you may get ui not found error.Get the selected ui object status and its informationCheck if the specific ui object existsd(text=&Settings&).exists # True if exists, else Falsed.exists(text=&Settings&) # alias of above property.Retrieve the info of the specific ui objectd(text=&Settings&).infoBelow is a possible result:{ u'contentDescription': u'',u'checked': False,u'scrollable': False,u'text': u'Settings',u'packageName': u'com.android.launcher',u'selected': False,u'enabled': True,u'bounds': {u'top': 385,& & & & & & u'right': 360,& & & & & & u'bottom': 585,& & & & & & u'left': 200},u'className': u'android.widget.TextView',u'focused': False,u'focusable': True,u'clickable': True,u'chileCount': 0,u'longClickable': True,u'visibleBounds': {u'top': 385,& & & & & & & & & & u'right': 360,& & & & & & & & & & u'bottom': 585,& & & & & & & & & & u'left': 200},u'checkable': False}Set/Clear text of editable fieldd(text=&Settings&).clear_text() &# clear the textd(text=&Settings&).set_text(&My text...&) &# set the textPerform the click action on the seleted ui objectPerform click on the specific ui object# click on the center of the specific ui objectd(text=&Settings&).click()# wait element show for 10 seconds(Default)d(text=&Settings&).click(timeout=10)# alias of click# short name for quick type with keyboardd(text=&Settings&).tap()# wait element show for 0 secondsd(text=&Settings&).tap_nowait()Perform long click on the specific ui object# long click on the center of the specific ui objectd(text=&Settings&).long_click()Gesture action for the specific ui objectDrag the ui object to another point or ui object# notes : drag can not be set until Android 4.3.# drag the ui object to point (x, y)d(text=&Settings&).drag_to(x, y, duration=0.5)# drag the ui object to another ui object(center)d(text=&Settings&).drag_to(text=&Clock&, duration=0.25)Two point gesture from one point to anotherd(text=&Settings&).gesture((sx1, sy1), (sx2, sy2), (ex1, ey1), (ex2, ey2))Two point gesture on the specific ui objectSupports two gestures:In , from edge to centerOut , from center to edge# notes : pinch can not be set until Android 4.3.# from edge to center. here is &In& not &in&d(text=&Settings&).pinch_in(percent=100, steps=10)# from center to edged(text=&Settings&).pinch_out()Wait until the specific ui appears or gone# wait until the ui object appearsd(text=&Settings&).wait(timeout=3.0) # return bool# wait until the ui object goned(text=&Settings&).wait_gone(timeout=1.0)Default timeout is 20s. see global settings for more detailsPerform fling on the specific ui object(scrollable)Possible properties:horiz or vertforward or backward or toBeginning or toEnd# fling forward(default) vertically(default)&d(scrollable=True).fling()# fling forward horizentallyd(scrollable=True).fling.horiz.forward()# fling backward verticallyd(scrollable=True).fling.vert.backward()# fling to beginning horizentallyd(scrollable=True).fling.horiz.toBeginning(max_swipes=1000)# fling to end verticallyd(scrollable=True).fling.toEnd()Perform scroll on the specific ui object(scrollable)Possible properties:horiz or vertforward or backward or toBeginning or toEnd , or to# scroll forward(default) vertically(default)d(scrollable=True).scroll(steps=10)# scroll forward horizentallyd(scrollable=True).scroll.horiz.forward(steps=100)# scroll backward verticallyd(scrollable=True).scroll.vert.backward()# scroll to beginning horizentallyd(scrollable=True).scroll.horiz.toBeginning(steps=100, max_swipes=1000)# scroll to end verticallyd(scrollable=True).scroll.toEnd()# scroll forward vertically until specific ui object appearsd(scrollable=True).scroll.to(text=&Security&)WatcherYou can register watcher to perform some actions when a selector can not find a match.Register WatcherWhen a selector can not find a match, uiautomator will run all registered watchers.Click target when conditions matchd.watcher(&AUTO_FC_WHEN_ANR&).when(text=&ANR&).when(text=&Wait&) \& & & & & & & & & & & & & & &.click(text=&Force Close&)# d.watcher(name) ## creates a new named watcher.# &.when(condition) &## the UiSelector condition of the watcher.# &.click(target) &## perform click action on the target UiSelector.Press key when conditions matchd.watcher(&AUTO_FC_WHEN_ANR&).when(text=&ANR&).when(text=&Wait&) \& & & & & & & & & & & & & & &.press(&back&, &home&)# d.watcher(name) ## creates a new named watcher.# &.when(condition) &## the UiSelector condition of the watcher.# &.press(&keyname&, ..., &keyname&.() &## press keys one by one in sequence.Check if the named watcher triggeredA watcher is triggered, which means the watcher was run and all its conditions matched.d.watcher(&watcher_name&).triggered# true in case of the specified watcher triggered, else falseRemove named watcher# remove the watcherd.watcher(&watcher_name&).remove()List all watchersd.watchers# a list of all registered wachers' namesCheck if there is any watcher triggeredd.watchers.triggered# &true in case of any watcher triggeredReset all triggered watchers# reset all triggered watchers, after that, d.watchers.triggered will be false.d.watchers.reset()Remvoe watchers# remove all registered watchersd.watchers.remove()# remove the named watcher, same as d.watcher(&watcher_name&).remove()d.watchers.remove(&watcher_name&)Force to run all watchers# force to run all registered watchersd.watchers.run()另外文档还是有很多没有写,推荐直接去看源码 init .pyGlobal settings# set delay 1.5s after each UI click and clickd.click_post_delay = 1.5 # default no delay# set default element wait timeout (seconds)d.wait_timeout = 30.0 # default 20.0中文字符的输入这种方法通常用于不知道控件的情况下的输入。第一步需要切换输入法,然后发送adb广播命令,具体使用方法如下d.set_fastinput_ime(True) # 切换成FastInputIME输入法d.send_keys(&你好123abcEFG&) # adb广播输入d.set_fastinput_ime(False) # 切换成正常的输入法测试方法$ adb forward tcp:9008 tcp:9008$ curl 127.0.0.1:9008/ping# expect: pong$ curl -d '{&jsonrpc&:&2.0&,&method&:&deviceInfo&,&id&:1}' 127.0.0.1:9008/jsonrpc/0# expect JSON outputUiautomator与Uiautomator2的区别api不同但也差不多Uiautomator2是安卓项目,而Uiautomator是java项目Uiautomator2可以输入中文,而Uiautomator的java工程需借助utf7输入法才能输入中文Uiautomator2必须明确EditText框才能向里面输入文字,Uiautomator直接指定父类也可以在子类中输入文字Uiautomator2获取控件速度快写,而Uiautomator获取速度慢一些;常见问题提示 502 错误尝试手机连接PC,然后运行下面的命令adb shell am instrument -w -r &-e debug false -e class com.github.uiautomator.stub.Stub \com.github.uiautomator.test/android.support.test.runner.AndroidJUnitRunner如果运行正常,启动测试之前增加一行代码 d.healthcheck()如果报错,可能是缺少某个apk没有安装,使用下面的命令重新初始化 python -m uiautomator2 init --reinstall尝鲜功能手机 python -muiautomator2 init 之后,浏览器输入 &手机IP:7912&,会发现一个远程控制功能,延迟非常低噢。^_^ABOUT项目重构自 https://github.com/openatx/atx-uiautomatorCHANGELOGAuto generated by pbr: CHANGELOG
相关技术文章
热门技术文章}

我要回帖

更多关于 APP和web一起做自动化怎么做 的文章

更多推荐

版权声明:文章内容来源于网络,版权归原作者所有,如有侵权请点击这里与我们联系,我们将及时删除。

点击添加站长微信