An article to get you started with Appium automated testing



Preface

Appium is a mobile automated testing tool that is often used to implement UI automated testing. It supports two major platforms, Android and IOS, and also supports a variety of programming, so it is widely used. Here is based on the Android platform, with the help of appium tool, using python language to implement simple automated testing.


1. Appium supports three types of applications

Native App: native application (an application developed for a specific mobile device or platform)
Mobile Web App: mobile web application (an application accessed through a mobile browser, such as IOS Safari, Chrome for Android)
Hybrid App: Hybrid application (mainly refers to applications developed using network technology and embedded into apps to run)


2. Design principles

Insert image description here
The core of appium is a C/S architecture. appium is equivalent to a web server, providing a set of interfaces. It will receive commands from the client, then run the commands on the mobile device, and finally return the results to the client through an HTTP response packet. Each time Each client will create a session after connecting to the server, and automation will be performed around a session. That is, appium starts a server on the PC, monitors the execution of automated tests from the client, and sends the request to the corresponding mobile device for execution.


3. Practical application of Appium

3. Set up a test environment

1.Install JDK

(1) The JDK package download URL is as follows: https://www.oracle.com/java/technologies/downloads/#jdk19-windows. Since the original URL is too slow to download, you can also consider using an open source software mirror station. Download
(2) Download version: There are currently versions 19, 17, 11, 8, etc. Just choose the appropriate one. The download here is version 1.8.0_282
(3) Installation: There are a lot of online tutorials, just install JDK and configure the environment variables
(4) After the installation is completed, use win+R to bring up the window terminal and enter java -version to check whether Installation successful

C:\Users\24637>java -version
openjdk version "1.8.0_282"
OpenJDK Runtime Environment (build 1.8.0_282-b08)
Eclipse OpenJ9 VM (build openj9-0.24.0, JRE 1.8.0 Windows 8.1 amd64-64-Bit 20210120_560 (JIT enabled, AOT enabled)
OpenJ9   - 345e1b09e
OMR      - 741e94ea8
JCL      - ab07c6a8fd based on jdk8u282-b08)

2.Install Android SDK

There are two ways to install the Android SDK, one is to download and install the SDK package directly, and the other is to install the SDK through Android Studio.
1. Download the SDK package and unzip it to the path you set, and configure the environment variables. The SDK package download URL is as follows: https://developer.android.google.cn/studio/releases/ platform-tools, you can also consider using the open source software mirror site to download
2. Install the SDK through Android Studio, select the path, configure the environment variables, and then start Android Studio to install the corresponding sdk package - currently The official website recommends downloading Android Studio including the Android SDK.
You can search online for detailed tutorials. The ultimate goal is to be able to use Android's adb function normally. After the installation is complete, use win+R to bring up the window terminal and enter adb --version to check whether the installation is successful.

C:\Users\24637>adb --version
Android Debug Bridge version 1.0.41
Version 33.0.3-8952118
Installed as E:\android-sdk_r24.4.1-windows\android-sdk-windows\platform-tools\adb.exe

3. Install the corresponding Python Client

appium Client supports multiple programming languages. Since the python language is used here, Python-Client is chosen here. The corresponding test library can be installed through the following two methods.
1. Win+R calls up window terminal input: pip install Appium-Python-Client

Enter pip list in the window terminal to check whether the corresponding package is installed:

C:\Users\24637>pip list
WARNING: Ignoring invalid distribution -ip (e:\python_3.10.2_64_bit\lib\site-packages)
Package                   Version
------------------------- ---------
adbutils                  0.15.2
altgraph                  0.17.3
apkutils2                 1.0.0
Appium-Python-Client      2.2.0
argcomplete               1.12.3

2. To install the pycharm software, just search and install Appium-Python-Client directly. Open the Settings menu > Projects > Python Interpreter > Add > Search for Appium-Python-Client, select it and click Install. After the installation is successful, You can see the corresponding package in the python interpreter.
Insert image description here

4. Install appium-desktop (server)

appium-desktop is mainly used as a server to monitor our mobile devices, receive JSON requests from the Client, and after parsing, drive the mobile device to run test cases. We can download the corresponding according to our own platform Version.
1. The appium-desktop download website is: https://github.com/appium/appium-desktop/releases/tag/v1.22.3-4. The window version is downloaded here. appium (Appium-Server-GUI-windows-1.22.3-4.exe)
2. After the download is completed, double-click to open the installation. After the installation is successful, an appium icon will be generated on the desktop and launched. The final interface is as shown in the figure below. By default, the monitored Host and Port are 0.0.0.0:4723. Click the Start "Server v1.22.3" button to start the Server and listen to the local port 4723.
Insert image description here

5. App Inspector

With the development of appium-desktop, the service of appium-desktop and the function of viewing elements have been separated. The latest version of appium-desktop currently only functions as a server, and the original function of viewing elements has been stripped out. Viewing element information requires Download Appium Inspector. The Appium Inspector download website is: https://github.com/appium/appium-inspector/releases. The version downloaded here is: Appium-Inspector-windows-2022.11.1.exe. The latest version is currently available, and you can Just download the latest version directly. Install directly after downloading. The interface after startup is as shown in the figure below.
Insert image description here

6. Install Android emulator

Android emulator, as the name suggests, is used to simulate Android devices to achieve simulated operation and debugging of Android devices. Commonly used Android emulators include: Android Studio emulator (official), genymotion, mumu, thunder, night god, Xiaoyao, etc., this The simulator used in the experiment is MuMu simulator. You can directly download it by entering the MuMu simulator website. The download website is: https://mumu.163.com/. After the download is completed, you can directly open it and use it. The interface is as follows.
Insert image description here


4. Basics of Appium

**This chapter mainly introduces some basics of Appium. You can also choose to start from Chapter 5 and implement a simple example of Appium first.

1.Desired Capabilities

Desired Capabilities is a dictionary object generated by the client. In appium, it mainly plays the role of telling the server App (the App under test) the running environment.

import time

from appium import webdriver
from appium.webdriver.common.appiumby import AppiumBy

# 定义Android运行环境
desired_caps = {
    
    
    "deviceName": "Android Emulator",  # 启动的设备
    "automationName": "Appium",  # 使用的自动化引擎,如appium(默认)或Selendroid
    "platformName": "Android",  # 使用的移动平台,如Android或IOs
    "platformVersion": "6.0.1",  # 指定的平台的系统版本,这里为安卓平台,版本7.0
    "appPackage": "com.android.settings",  # 被测试App的Package名
    "appActivity": ".Settings",  # 被测试App的Activity名
    "unicodeKeyboard": True,  # 设置中文键盘
    "resetKeyboard": True,  # 重置自动化时设置的键盘
}
driver = webdriver.Remote('http://localhost:4723/wd/hub', desired_caps)

# 1、使用ID定位(点击搜索)
driver.find_element(AppiumBy.ID, "com.android.settings:id/search").click()

As shown in the above code, the Desired Capabilities dictionary has set the relevant parameters required by the software to be tested. Each dictionary element has its fixed role. The above are just some of the most commonly used parameters. If you want to know more For configuration parameter description, please refer to the official documentation:
http://appium.io/docs/en/writing-running-appium/caps/

2. Control positioning

(1) Use ID positioning
Insert image description here
ID positioning uses the resource-id of the control for positioning. The resource-id can be viewed through the Appium Inspector tool, as shown in the figure above, resource-id The driver.find_element() function is used to use it. You can use it after installing and importing the corresponding library. Please pay attention to distinguish the AppiumBy module and the By module. The By module is generally used for web testing, so if you use the By module, it will cause Some positioning methods cannot be recognized, so here we just use AppiumBy.
The method is as follows:

from appium import webdriver
from appium.webdriver.common.appiumby import AppiumBy
# from selenium.webdriver.common.by import By

desired_caps = {
    
    
	...
	...
}
driver = webdriver.Remote('http://localhost:4723/wd/hub', desired_caps)

# 1、使用ID定位(点击搜索)
driver.find_element(AppiumBy.ID, "com.android.settings:id/search").click()
time.sleep(1)

(2) Use Class Name to locate
Insert image description here
Position through the class attribute of the control. You can view the class attribute of the control through the Appium Inspector tool (as shown in the figure above). If you encounter The class attribute of multiple elements has the same name. We can use the driver.find_elements() function to first locate a group of controls and then further filter to find the control we want to operate. Here is how to use class to locate a control: < /span>

from appium import webdriver
from appium.webdriver.common.appiumby import AppiumBy
# from selenium.webdriver.common.by import By

desired_caps = {
    
    
	...
	...
}
driver = webdriver.Remote('http://localhost:4723/wd/hub', desired_caps)

# 2、使用Class Name定位(点击退出搜索)
driver.find_element(AppiumBy.CLASS_NAME, "android.widget.ImageButton").click()
time.sleep(1)

(3) Use XPath to locate the control
Insert image description here
The usage on appium is very powerful, but it is a bit too long. It can be used in actual application scenarios. The usage method is as follows:

from appium import webdriver
from appium.webdriver.common.appiumby import AppiumBy
# from selenium.webdriver.common.by import By

desired_caps = {
    
    
	...
	...
}
driver = webdriver.Remote('http://localhost:4723/wd/hub', desired_caps)

# 3、使用XPath定位(点击显示)
driver.find_element(AppiumBy.XPATH, "/hierarchy/android.widget.FrameLayout/android.view.ViewGroup/android.widget.FrameLayout[2]/android.widget.FrameLayout/android.widget.ScrollView/android.widget.LinearLayout/android.widget.LinearLayout[2]/android.view.ViewGroup/android.widget.FrameLayout[1]/android.widget.LinearLayout/android.widget.LinearLayout/android.widget.LinearLayout").click()
time.sleep(1)

(4) Use Accessibility id positioning
Insert image description here
In Android, Accessibility id positioning takes the content-desc attribute of the control. The corresponding attributes can also be viewed through the Appium Inspector tool (as shown above) shown), the usage method is as follows:

from appium import webdriver
from appium.webdriver.common.appiumby import AppiumBy
# from selenium.webdriver.common.by import By

desired_caps = {
    
    
	...
	...
}
driver = webdriver.Remote('http://localhost:4723/wd/hub', desired_caps)

# 4、使用Accessibility id定位
driver.find_element(AppiumBy.ACCESSIBILITY_ID, "向上导航").click()
time.sleep(1)

(4) Use Android uiautomator positioning
Android uiautomator positioning is an extended positioning method of appium and only supports the Android platform; Android uiautomator can directly use the positioning method of UIAutomator2 to find controls , since it uses the UIAutomator2 test library, the positioning of the control can also be achieved through the corresponding properties. It means that the corresponding properties can also be viewed through the Appium Inspector tool (as shown in the picture above). Here are some examples. Common attribute positioning methods are as follows:

import time
from appium import webdriver
from appium.webdriver.common.appiumby import AppiumBy
# from selenium.webdriver.common.by import By

desired_caps = {
    
    
	...
	...
}
driver = webdriver.Remote('http://localhost:4723/wd/hub', desired_caps)

# 5、使用Android uiautomator定位,属于appium的扩展定位方法,且只支持Android平台
driver.find_element(AppiumBy.ANDROID_UIAUTOMATOR, 'new UiSelector().text("网易新闻")').click()  #text属性,匹配全部
time.sleep(10)
driver.find_element(AppiumBy.ANDROID_UIAUTOMATOR, 'new UiSelector().textContains("登录")').click()  #text属性,匹配部分
time.sleep(1)
driver.find_element(AppiumBy.ANDROID_UIAUTOMATOR, 'new UiSelector().textStartsWith("我的钱")').click()  #text属性,匹配开头
time.sleep(1)
driver.find_element(AppiumBy.ANDROID_UIAUTOMATOR, 'new UiSelector().description("返回")').click()   #content-desc属性
time.sleep(1)
driver.find_element(AppiumBy.ANDROID_UIAUTOMATOR, 'new UiSelector().resourceId("com.netease.newsreader.activity:id/lb")').click()   #id属性
time.sleep(1)
driver.find_element(AppiumBy.ANDROID_UIAUTOMATOR, 'new UiSelector().className("android.widget.TextView")').click()  #class属性
time.sleep(1)
driver.find_element(AppiumBy.ANDROID_UIAUTOMATOR, 'new UiSelector().className("android.widget.EditText")').send_keys("hello world!")  #class属性,(.TextView)元素不能用于输入,(.EditText)元素才能定位后输入

There are many ways to position UIAutomator. The above briefly lists its usage of text attributes, content-desc attributes, id attributes, and class attributes. If you are interested in learning more, you can view the official documentation. The link is as follows: https: //developer.android.google.cn/training/testing/ui-automator

(4) Other positioning

#6、Web APP下,或者Hybrid APP(混合应用)的WebView组件下使用
driver.find_element(AppiumBy.NAME, "").click()
driver.find_element(AppiumBy.TAG_NAME, "").click()
driver.find_element(AppiumBy.LINK_TEXT, "").click()
driver.find_element(AppiumBy.PARTIAL_LINK_TEXT, "").click()
driver.find_element(AppiumBy.CSS_SELECTOR, "").click()
time.sleep(1)
#7、前面三个是IOS的定位,后4个不常用,这里就不做介绍了
driver.find_element(AppiumBy.IOS_UIAUTOMATION, "").click()
driver.find_element(AppiumBy.IOS_PREDICATE, "").click()
driver.find_element(AppiumBy.IOS_CLASS_CHAIN, "").click()
driver.find_element(AppiumBy.ANDROID_VIEWTAG, "").click()
driver.find_element(AppiumBy.ANDROID_DATA_MATCHER, "").click()
driver.find_element(AppiumBy.IMAGE, "").click()
driver.find_element(AppiumBy.CUSTOM, "").click()

There are many actual positioning methods. I will briefly list a few of the most common methods. Other methods can be continued to be learned and expanded in practice.

3. Common APIs of appium

(1) Application operation

1. driver.install_app("Application package name path") #Install app
2. driver.remove_app("Application package name") #Uninstall app< a i=2> 3. driver.terminate_app("Application package name") #Close app 4. driver.activate_app("Application package name") #Open app 5. result = driver.is_app_installed("Application package name") #Determine whether the app is installed print(result) 6. driver.background_app(10 ) #Return to the background Appium can implement various operations on app applications through the above corresponding functions, such as installation, uninstallation, closing, opening, etc. Examples are as follows:





import time
from appium import webdriver
from appium.webdriver.common.appiumby import AppiumBy

desired_caps = {
    
    
	...
	...
}
driver = webdriver.Remote('http://localhost:4723/wd/hub', desired_caps)

driver.terminate_app("com.android.settings")    #关闭设置应用
time.sleep(1)
if driver.is_app_installed("com.adsk.sketchbook"):  #判断应用是否已安装
    driver.remove_app("com.adsk.sketchbook")      #卸载应用
    print("卸载书写软件成功!")
else:
    driver.install_app("C:/Users/24637/Desktop/自动化测试常用软件/com.adsk.sketchbook_5.2.5_liqucn.com.apk")    #安装应用
    print("软件不存在,正在安装。。。")
driver.activate_app("com.netease.newsreader.activity")
driver.background_app(5)    #退至后台

(2) Context operation
1. contexts = driver.contexts #Get all currently available contexts
print(contexts)< a i=3> 2. current_context = driver.current_context #Get the current context print(current_context) 3. driver.switch_to.context('NATIVE_APP') # Switch context


import time
from appium import webdriver
from appium.webdriver.common.appiumby import AppiumBy

desired_caps = {
    
    
	...
	...
}
driver = webdriver.Remote('http://localhost:4723/wd/hub', desired_caps)

#上下文操作
contexts = driver.contexts  #获取当前所有可用上下文
print(contexts)
current_context = driver.current_context  #获取当前上下文
print(current_context)
# driver.switch_to.context('NATIVE_APP')   #切换上下文

Context is an ordered sequence of attributes that defines the environment for objects residing in the environment. The context in appium is mainly aimed at hybrid applications. They are related to App native controls and elements on embedded Web pages. The positioning methods are different, so you need to confirm the context of the currently operated element or control in order to use different positioning strategies
(3) Keyboard input
1. driver. keyevent(key-value code)

import time
from appium import webdriver
from appium.webdriver.common.appiumby import AppiumBy

desired_caps = {
    
    
	...
	...
}
driver = webdriver.Remote('http://localhost:4723/wd/hub', desired_caps)

driver.activate_app("com.netease.newsreader.activity")  #打开网易新闻应用
time.sleep(5)

driver.find_element(AppiumBy.ANDROID_UIAUTOMATOR, 'new UiSelector().className("android.widget.TextView")').click()  #点击搜索
time.sleep(1)	
driver.find_element(AppiumBy.ANDROID_UIAUTOMATOR, 'new UiSelector().className("android.widget.EditText")').send_keys("jack!") 	 #输入jack
time.sleep(1)
#键值输入186
driver.keyevent(8)
driver.keyevent(15)
driver.keyevent(13)
#键值输入hello
driver.keyevent(36)
driver.keyevent(33)
driver.keyevent(40)
driver.keyevent(40)
driver.keyevent(43)

After positioning the cursor to an input box, it automatically enters the keyboard input mode, executes the keyevent() method, and enters the corresponding character number. This is the usage of the key-value function. The above is just a brief list of the usage of some key values. For more key value information, please refer to the following website: https://developer.android.google.cn/reference/android/view/KeyEvent
(4) Touch operation TouchAction
1. Touch and click operation
The touch and click operation function TouchAction(driver).tap() mainly has three parameters, the coordinate point ( x=33, y=86), control element (element = el) and number of clicks (count = 2). By operating these three parameters, you can use coordinates or controls for touch positioning and click and double-click. Touch and click function, its specific usage examples are as follows:

from appium import webdriver
from appium.webdriver.common.appiumby import AppiumBy
from appium.webdriver.common.touch_action import TouchAction

desired_caps = {
    
    
	...
	...
}
driver = webdriver.Remote('http://localhost:4723/wd/hub', desired_caps)

driver.activate_app("com.netease.newsreader.activity")  #打开网易新闻应用
time.sleep(15)

#通过控件实现触摸
el = driver.find_element(AppiumBy.ID, "com.netease.newsreader.activity:id/c52")
actions = TouchAction(driver).tap(element=el)
actions.perform()

#通过坐标点实现触摸
actions = TouchAction(driver)
actions.tap(x=333, y=609)
actions.perform()

#双击
actions = TouchAction(driver)
actions.tap(x=333, y=609,count=2) #count为点击次数
actions.perform()

2. Touch and hold

from appium import webdriver
from appium.webdriver.common.appiumby import AppiumBy
from appium.webdriver.common.touch_action import TouchAction

desired_caps = {
    
    
	...
	...
}
driver = webdriver.Remote('http://localhost:4723/wd/hub', desired_caps)

driver.terminate_app("com.android.settings")
#长按控件
el = driver.find_element(AppiumBy.ANDROID_UIAUTOMATOR,'text("网易新闻")')
TouchAction(driver).long_press(el, duration=2000).perform()
TouchAction(driver).long_press(x=521, y=349, duration=2000).perform()

3. Move
Move the cursor to a new element or coordinate point. It can also be positioned through controls and coordinates, and then moved. The function is as follows:

#移动
el = driver.find_element(AppiumBy.ANDROID_UIAUTOMATOR,'text("CIBN酷喵")') #通过控件定位
TouchAction(driver).move_to(el).perform()
TouchAction(driver).move_to(x=523, y=507).perform() #通过坐标定位

4. Pause
Pause the execution of the script, wait(self,ms=0), the unit is milliseconds

TouchAction(driver).wait(5000).perform()

5. Multi-touch execution
Appium can not only perform one action, but also perform multiple actions at the same time to form an action chain and simulate the actions of multiple finger touches. Appium needs By constructing a MultiAction object to perform multiple actions. Write by importing the MultiAction library as follows:

from appium import webdriver
from appium.webdriver.common.touch_action import TouchAction
from appium.webdriver.common.multi_action import MultiAction

desired_caps = {
    
    
	...
	...
}
driver = webdriver.Remote('http://localhost:4723/wd/hub', desired_caps)

driver.terminate_app("com.android.settings")
time.sleep(3)

#同时执行多个动作 MultiAction
a1 = TouchAction()
a1.press(x=243,y=184)
a1.move_to(x=930, y=184)
a1.release()

a2 = TouchAction()
a2.long_press(x=243,y=342)
a2.move_to(x=930, y=342)
a2.release()

ma = MultiAction(driver)
ma.add(a1, a2)
ma.perform()

(5) Special operations
1. Get the package name (package) of the current App, only supports Android

package = driver.current_package
print(package)

2. Get the activity of the current App, only supports Android

activity = driver.current_activity
print(activity)

3. Put away the keyboard (some clients may not work)

activity = driver.current_activity
print(activity)

4. Screen pause (some clients may not work)

driver.lock(seconds=1)

5. Get the screen width and height

windows = driver.get_window_size()
print(windows["width"])
print(windows["height"])

6. Pull the file
Pull the file to the device. It should be noted here that the data format is base64 encoded, so the encoding and decoding process needs to be performed here and imported. base64 library.

import base64

file_base64 = driver.pull_file('/sdcard/1.txt').encode()	#encode()函数,将字符串Str类型数据转换成bytes数据类型
file_base64 = base64.decodebytes(file_base64)	#这里是把bytes的数据进行base64解码,解码成功后,返回的数据类型为bytes
print(file_base64.decode())	#把bytes数据类型转换成Str数据类型,并打印出来

7. Push files
Push files to the device

import base64

data = "some data for the file"
data = base64.b64encode(data.encode('utf8'))	#编码成base64数据,并转换成bytes格式的数据
path = "/sdcard/1.txt"
driver.push_file(path, data.decode())	#把数据推送到设备里面

The above are the usage of some common APIs of appium. If you want to know more about the API interface information, you can also directly enter the following website to query. Basically, all related API usage methods can be found there. The link to Appium’s API interface documentation is as follows: https://appium.io/docs/en/about-appium/api/
In addition, if you want to know more about appium, you can also check it out on the official website For its related information, the appium official website link is as follows: http://appium.io/docs/en/about-appium/intro/

4. App Inspector

Regarding the use of Appium Inspector, here we mainly explain its two basic functions, the function of obtaining control information of elements and recording scripts. Its specific usage is as follows.
(1) Function of obtaining elements
When explaining the positioning method of elements above, obtaining the relevant control parameters of the App is also implemented through the Appium Inspector. Here Let’s briefly explain how to use it.
1. Start the MuMu emulator, win + r, enter cmd to enter the window terminal, enter: "adb connect 127.0.0.1:7555" to connect to the Android emulator

C:\Users\24637>adb connect 127.0.0.1:7555
* daemon not running; starting now at tcp:5037
* daemon started successfully
connected to 127.0.0.1:7555

2. Start Appium Server GUI
Click to open it directly, then click to start the server
Insert image description here
3. Start Appium Inspector
As shown in the above picture, set the IP and port, and set the Desired Capabilities parameter values ​​according to the environment in which the terminal App runs, and click Run.
Insert image description here
4. Obtain control element information
After successfully starting Appium Inspector, you will enter the above interface, select the view element mode, and move the cursor to the corresponding App element , the corresponding element control information will appear on the right
Insert image description here
(2) The function of recording scripts
Recording scripts can also be divided into operating elements based on coordinates and operating based on controls. Two major contents of elements
Insert image description here
1. Manipulate elements through coordinates - click
Click the eye-like button in the middle to open the recording function and switch the mode to the mode of clicking the coordinate point , click the coordinate element of the client, and the corresponding code will be displayed in the recording display box on the right. As shown in the figure above, if you click Execute multiple times in succession, the corresponding automated test script will be generated. Copy and paste it into python to run it. Can.

#此处为点击后,生成的代码
actions = ActionChains(driver)
actions.w3c_actions = ActionBuilder(driver, mouse=PointerInput(interaction.POINTER_TOUCH, "touch"))
actions.w3c_actions.pointer_action.move_to_location([object Object], undefined)
actions.w3c_actions.pointer_action.pointer_down()
actions.w3c_actions.pointer_action.pause(0.1)
actions.w3c_actions.pointer_action.release()
actions.perform()

Pay attention to two points here. The first point is: when copying the code, you need to choose to display all the code and copy all the code instead of transplanting only one function; the second point is: as shown in the code shown above, get The coordinates of the function are ([object Object], undefined). If you transplant it to python and run it, an error will be reported. You need to manually enter the coordinate value of the click, that is, change it to the following code:

actions.w3c_actions.pointer_action.move_to_location(179,282)

2. Manipulate elements through coordinates - sliding
Insert image description here
Turn on the recording function, switch the mode to the sliding coordinate mode, first select a point, and then select a point to implement the sliding operation, the same The corresponding sliding code is generated as follows

#此处为滑动后,生成的代码
actions = ActionChains(driver)
actions.w3c_actions = ActionBuilder(driver, mouse=PointerInput(interaction.POINTER_TOUCH, "touch"))
actions.w3c_actions.pointer_action.move_to_location([object Object], undefined)
actions.w3c_actions.pointer_action.pointer_down()
actions.w3c_actions.pointer_action.move_to_location(undefined, undefined)
actions.w3c_actions.pointer_action.release()
actions.perform()

Same as above, copy all the code to python, change the coordinate value in the corresponding function, and the sliding operation can be realized.

actions.w3c_actions.pointer_action.move_to_location(714,822)

actions.w3c_actions.pointer_action.move_to_location(714,307)

3. Manipulate elements through controls - click
Insert image description here
to open the recording function, switch the mode to the mode of selecting elements, select an element, and use the gadget in the selected element on the right to achieve it Click function.

#通过控件点击搜索设置
el2 = driver.find_element(by=AppiumBy.ACCESSIBILITY_ID, value="搜索设置")
el2.click()

The advantage of operating through controls is that you do not need to manually change the coordinates of the code. You can directly copy all the code to python to run the code.

4. Manipulate elements through controls - send keys
Insert image description here
Turn on the recording function, switch the mode to the mode of selecting elements, click to select, and enter the input box, use the selection on the right The widget in a certain element implements the function of entering the key 'hello'.

#点击搜索框,并切换至输入模式,输入hello
el1 = driver.find_element(by=AppiumBy.ACCESSIBILITY_ID, value="搜索设置")
el1.click()
el2 = driver.find_element(by=AppiumBy.ID, value="android:id/search_src_text")
el2.click()
time.sleep(1)	#增加的延时
el2.send_keys("hello")

When using a key, make sure the input box is positioned. Copy all the code to python, and you may get an error when you enter the key. This is most likely because the command is executed too fast, and the input box of the App has not fully reacted before executing the input. At this time, you can manually add A delay allows the code to run.
In addition to the basic usage introduced above, there are other detailed functions of the application. I won’t introduce them in detail here. The tool class requires more operations and more attempts. As long as you have mastered automatic script recording and transplantation, Just run it in python, and other detailed functions can be discovered while using it.

5. Practical application of Appium

After the previous introduction, everyone can basically get started with appium. Let’s use what we have learned previously to implement the following UI automation content: Run the script, enter the Settings App > Click
(1) Start the MuMu Android emulator
Since the automated script edited below uses NetEase News, you can also download the NetEase News apk first and install it.
Insert image description here
(2) Start Appium Server GUI
Insert image description here
(3) Win + r, enter cmd to enter the window terminal, enter: "adb connect 127.0.0.1:7555" to connect Android emulator
Insert image description here
(4) Click to open Appium Inspector and get the control elements
Insert image description here
(5) Open PyCharm and enter the following code to run the previous (1)-(4) The content and operation methods have been introduced before. Here we will directly introduce the practical operation of code editing. After the environment is set up, you can start writing code. Here, combined with the above content, we use the basic knowledge learned above to base on Native settings menu and NetEase News apk, write a simple and complete example as follows:

import time
from appium import webdriver
from appium.webdriver.common.appiumby import AppiumBy

# 定义Android运行环境
desired_caps = {
    
    
    "deviceName": "Android Emulator",  # 启动的设备
    "automationName": "Appium",  # 使用的自动化引擎,如appium(默认)或Selendroid
    "platformName": "Android",  # 使用的移动平台,如Android或IOs
    "platformVersion": "6.0.1",  # 指定的平台的系统版本,这里为安卓平台,版本6.0.1
    "appPackage": "com.android.settings",  # 被测试App的Package名
    "appActivity": ".Settings",  # 被测试App的Activity名
    "unicodeKeyboard": True,  # 设置中文键盘
    "resetKeyboard": True,  # 重置自动化时设置的键盘
}

driver = webdriver.Remote('http://localhost:4723/wd/hub', desired_caps)
# 1、使用ID定位(点击搜索)
driver.find_element(AppiumBy.ID, "com.android.settings:id/search").click()
time.sleep(1)
# 2、使用Class Name定位(点击退出搜索)
driver.find_element(AppiumBy.CLASS_NAME, "android.widget.ImageButton").click()
time.sleep(1)
# 3、使用XPath定位(点击显示)
driver.find_element(AppiumBy.XPATH, "/hierarchy/android.widget.FrameLayout/android.view.ViewGroup/android.widget.FrameLayout[2]/android.widget.FrameLayout/android.widget.ScrollView/android.widget.LinearLayout/android.widget.LinearLayout[2]/android.view.ViewGroup/android.widget.FrameLayout[1]/android.widget.LinearLayout/android.widget.LinearLayout/android.widget.LinearLayout").click()
time.sleep(1)
# 4、使用Accessibility id定位(点击返回)
driver.find_element(AppiumBy.ACCESSIBILITY_ID, "向上导航").click()
time.sleep(1)
# 5、使用ID定位(点击搜索)
driver.find_element(AppiumBy.ID, "com.android.settings:id/search").click()
time.sleep(1)
# 6、使用CLSS_NAME定位,输入hello
driver.find_element(AppiumBy.CLASS_NAME, "android.widget.EditText").send_keys("hello")
time.sleep(3)
# 7、退出设置菜单
driver.terminate_app("com.android.settings")
# 使用Android uiautomator定位,属于appium的扩展定位方法,且只支持Android平台
# 8、text属性,匹配全部,识别到网易新闻,并点击
driver.find_element(AppiumBy.ANDROID_UIAUTOMATOR, 'new UiSelector().text("网易新闻")').click()
time.sleep(15)
# 9、text属性,匹配部分,识别到部分内容,并点击
driver.find_element(AppiumBy.ANDROID_UIAUTOMATOR, 'new UiSelector().textContains("登录")').click()
time.sleep(1)
# 10、text属性,匹配开头,识别开头文字,并点击
driver.find_element(AppiumBy.ANDROID_UIAUTOMATOR, 'new UiSelector().textStartsWith("我的钱")').click()
time.sleep(1)
# 11、content-desc属性,根据content-desc属性识别,点击返回
driver.find_element(AppiumBy.ANDROID_UIAUTOMATOR, 'new UiSelector().description("返回")').click()
time.sleep(1)
# 12、id属性,根据id属性识别,点击返回首页
driver.find_element(AppiumBy.ANDROID_UIAUTOMATOR, 'new UiSelector().resourceId("com.netease.newsreader.activity:id/lb")').click()
time.sleep(1)
# 13、class属性,根据class属性识别,点击输入框
driver.find_element(AppiumBy.ANDROID_UIAUTOMATOR, 'new UiSelector().className("android.widget.TextView")').click()
time.sleep(1)
# 14、class属性,(.TextView)元素不能用于输入,(.EditText)元素才能定位后输入,根据class属性识别,进入输入框输入模式,输入hello world!
driver.find_element(AppiumBy.ANDROID_UIAUTOMATOR, 'new UiSelector().className("android.widget.EditText")').send_keys("hello world!")
time.sleep(5)
# 15、退出网易新闻
driver.terminate_app("com.netease.newsreader.activity")

The video of the script running effect is as follows:

Script running effect

6. Summary

At this point, this is a brief introduction to using Appium. The master will lead you in. The practice depends on the individual, combined with the actual situation, and the flexible use of technology is the way to go. Chongya, social animals, boring life needs to be reconciled with knowledge.

Guess you like

Origin blog.csdn.net/qq_46166916/article/details/129106585