跪求appium xpath 语法iOS 基于python 的滑屏和坐标点击语法,求指教

appium在真机上运作IOS实例要注意的几点:包括python和java运行log 和部分关键代码 - 操作系统当前位置:& &&&appium在真机上运作IOS实例要注意的几点:包括pythoappium在真机上运作IOS实例要注意的几点:包括python和java运行log 和部分关键代码&&网友分享于:&&浏览:1次appium在真机上运行IOS实例要注意的几点:包括python和java运行log 和部分关键代码最近在研究appium对于IOS的自动化测试,发现在真机上运行appium提供的开源的例子遇到了几个block,询问了一个这个方便面的高手并且总结网上搜到的帖子,现在综合一下。
appium 在模拟器中跑,只需要注意:
1:app=path找到编译后app所在的位置,如:注意Release-iphonesimulator这个是模拟器编译后的文件夹
& & final File appDir = new File(System.getProperty(&user.dir&),
& & & & &../../../apps/TestApp/build/Release-iphonesimulator&);
& & final File app = new File(appDir, &TestApp.app&);
& & capabilities.setCapability(&app&, app.getAbsolutePath());
appium真机上运行:
1:运行的时候要将APP安装到真机上面
2:运行的时候,不能再开instrument&
3:命令行里面启动的时候,参数写错了应该是 appium -U 3d2cad5aa98a2cccddd1c --app io.appium &然后代码里面 app=bundleID,如以下例子中:& capabilities.setCapability(&app&, &io.appium.TestApp&);而不是那个很长的路径,其中-U 参数后面是真机的uuid,可以打开xcode,在windows下的organise下找到,一般mac连接上ipad后会有绿色圆点
现在贴上真机上运行python实例:
Kingsons-MacBook:Study kingson$ appium -U 1a601f5cd791bcfc81cd69b --app com.telenavsoftware.doudouy
info: Welcome to Appium v0.11.4 (REV b04decde9bfcd04a036)
info: Appium REST http interface listener started on 0.0.0.0:4723
- socket.io started
debug: Appium request initiated at /wd/hub/session
debug: Request received with params: {&sessionId&:null,&desiredCapabilities&:{&device&:&iPhone Simulator&,&platform&:&Mac&,&browserName&:&iOS&,&version&:&7.0&,&app&:&com.telenavsoftware.doudouy&}}
info: App is an iOS bundle, will attempt to run as pre-existing
info: Creating new appium session a36fdf63-9b22-48a4-bb01-4b44ddb54aff
info: Removing any remaining instruments sockets
info: Cleaned up instruments socket /tmp/instruments_sock
info: Cleaning up any tracedirs
info: No tracedirs to clean up
info: Localizable.strings is not currently supported when using real devices.
info: Not setting device type since we're connected to a device
info: Starting iOS device log capture via idevicesyslog
debug: Real device specified but no ipa, assuming bundle ID is on device
debug: Creating instruments
info: instruments is: /Applications/Xcode.app/Contents/Developer/usr/bin/instruments
info: [INSTSERVER] Instruments socket server started at /tmp/instruments_sock
info: Attempting to run app on real device with UDID 1a601f5cd791bcfc81cd69b
info: Spawning instruments with command: /Applications/Xcode.app/Contents/Developer/usr/bin/instruments -t /Applications/Xcode.app/Contents/Applications/Instruments.app/Contents/PlugIns/AutomationInstrument.bundle/Contents/Resources/Automation.tracetemplate -w 1a601f5cd791bcfc81cd69b com.telenavsoftware.doudouy -e UIASCRIPT /usr/local/lib/node_modules/appium/lib/devices/ios/uiauto/bootstrap.js -e UIARESULTSPATH /tmp/appium-instruments/
info: And extra without-delay env: {}
info: And launch timeout: 90000ms
info: [INST STDERR]
10:40:22.536 instruments[] Connection to the remote device lost while launching target. Aborting...
info: [INST STDERR]
10:40:22.539 instruments[] Recording cancelled : At least one tar aborting run
info: [INST STDERR] Instruments Trace Error : Error Domain=com.apple.instruments Code=1 &Error Starting Recording& UserInfo=0x7ff6d308f220 {NSLocalizedDescription=Error Starting Recording, NSLocalizedRecoverySuggestion=At least one tar aborting run}
Instruments Trace Error : Failed to start trace.
info: [INSTSERVER] Instruments exited with code 253
error: Instruments did not launch successfully, failing session
info: Cleaning up appium session
error: Failed to start an Appium session, err was: Error: Instruments did not launch successfully--please check your app paths or bundle IDs and try again
info: Responding to client with error: {&status&:33,&value&:{&message&:&A new session could not be created. (Original error: Instruments did not launch successfully--please check your app paths or bundle IDs and try again)&,&origValue&:&Instruments did not launch successfully--please check your app paths or bundle IDs and try again&},&sessionId&:null}
POST /wd/hub/session 500 6015ms - 342b```
我的部分代码片段:
class TestSequenceFunctions(unittest.TestCase):
def setUp(self):
# set up appium
app = &com.telenavsoftware.doudouy&
#app = os.path.join(os.path.dirname(__file__),
'../../apps/DDY/build/',
'DouDouY.app')
#app = os.path.abspath(app)
self.driver = webdriver.Remote(
command_executor='http://127.0.0.1:4723/wd/hub',
desired_capabilities={
'browserName': 'iOS',
'device': 'iPhone Simulator',
'platform': 'Mac',
'version': '7.0',
'app': app
1.启动Appium时,保证你的Real
Device的UDID和你的应用的Bundle ID正确
2.确保你的应用可以安装到你的真机上
3.安装后请断开与Xcode的连接
4.确保Mac上没有启动Instruments工具
以下是JAVA真机运行log:
devexus-iMac:build devexu$
appium -U 3d2cad5aa98a2cccddd1c --app io.appium
info: Welcome to Appium v1.1.0 (REV e433bbcdb2bcb32117)
info: Appium REST http interface listener started on 0.0.0.0:4723
info: socket.io started
info: Non-default server args: {&app&:&io.appium&,&udid&:&3d2cad5aa98a2cccddd1c&}
debug: Appium request initiated at /wd/hub/session
debug: Request received with params: {&desiredCapabilities&:{&platformVersion&:&7.1&,&app&:&io.appium.TestApp&,&platformName&:&iOS&,&deviceName&:&iPhone Simulator&,&browserName&:&&}}
info: App is an iOS bundle, will attempt to run as pre-existing
info: Creating new appium session 2bcd619b-b7fb-45f5-b20c-79caff8cd24f
info: Removing any remaining instruments sockets
info: Cleaned up instruments socket /tmp/instruments_sock
info: Cleaning up any tracedirs
info: No tracedirs to clean up
info: Setting Xcode folder
info: Setting Xcode version
info: Setting iOS SDK Version
info: iOS SDK Version set to 7.1
info: Detecting automation tracetemplate
info: Not auto-detecting udid, running on sim
info: Localizable.strings is not currently supported when using real devices.
info: Not setting locale because we're using a real device
debug: Creating instruments
info: Not setting iOS and app preferences since we're on a real device
info: Starting iOS device log capture via idevicesyslog
info: Not setting device type since we're connected to a device
debug: Real device specified but no ipa or app path, assuming bundle ID is on device
debug: Starting instruments
info: Instruments is at: /Applications/Xcode.app/Contents/Developer/usr/bin/instruments
info: [INSTSERVER] Instruments socket server started at /tmp/instruments_sock
info: Attempting to run app on real device with UDID 3d2cad5aa98a2cccddd1c
info: Spawning instruments with command: /Applications/Xcode.app/Contents/Developer/usr/bin/instruments -t /Applications/Xcode.app/Contents/Applications/Instruments.app/Contents/PlugIns/AutomationInstrument.bundle/Contents/Resources/Automation.tracetemplate
-w 3d2cad5aa98a2cccddd1c io.appium.TestApp -e UIASCRIPT /usr/local/lib/node_modules/appium/node_modules/appium-uiauto/uiauto/bootstrap.js -e UIARESULTSPATH /tmp/appium-instruments
info: And extra without-delay env: {}
info: And launch timeouts (in ms): {&global&:90000}
info: [INST]
01:29:30 +0000 Start: Bootstrapping uiauto
info: [INST]
01:29:32 +0000 Start: Got user: devexu
info: [INST]
01:29:33 +0000 Start: Not using settings file.
info: [INST]
01:29:33 +0000 Start: isVerbose:false
info: [INST]
01:29:37 +0000 Start: Using node at: /usr/local/bin/node
info: [INSTSERVER] Instruments is ready to receive commands
info: Instruments launched. Starting poll loop for new commands.
info: Setting bootstrap config keys/values
info: Pushing command to appium work queue: &setBootstrapConfig: autoAcceptAlerts=false&
debug: Sending command to instruments: setBootstrapConfig: autoAcceptAlerts=false
info: [INSTSERVER] Socket data received (15 bytes)
info: [INSTSERVER] Socket data being routed for 'cmd' event
info: [INSTSERVER] Sending command to instruments: setBootstrapConfig: autoAcceptAlerts=false
info: [INSTSERVER] Socket data received (48 bytes)
info: [INSTSERVER] Socket data being routed for 'cmd' event
info: [INSTSERVER] Got result from instruments: {&status&:0,&value&:&&}
info: Setting initial orientation to PORTRAIT
info: Pushing command to appium work queue: &au.setScreenOrientation('PORTRAIT')&
debug: Sending command to instruments: au.setScreenOrientation('PORTRAIT')
info: [INSTSERVER] Sending command to instruments: au.setScreenOrientation('PORTRAIT')
info: [INST]
01:29:41 +0000 Debug: target.setDeviceOrientation(&1&)
info: [INSTSERVER] Socket data received (56 bytes)
info: [INSTSERVER] Socket data being routed for 'cmd' event
info: [INSTSERVER] Got result from instruments: {&status&:0,&value&:&PORTRAIT&}
info: Device launched! Ready for commands
info: Setting command timeout to the default of 60 secs
info: Appium session started with sessionId 2bcd619b-b7fb-45f5-b20c-79caff8cd24f
POST /wd/hub/session 303 22483ms - 9b
debug: Appium request initiated at /wd/hub/session/2bcd619b-b7fb-45f5-b20c-79caff8cd24f
debug: Request received with params: {}
info: Responding to client with success: {&status&:0,&value&:{&webStorageEnabled&:false,&locationContextEnabled&:false,&browserName&:&&,&platform&:&MAC&,&javascriptEnabled&:true,&databaseEnabled&:false,&takesScreenshot&:true,&warnings&:{},&desired&:{&platformVersion&:&7.1&,&app&:&io.appium.TestApp&,&platformName&:&iOS&,&deviceName&:&iPhone
Simulator&,&browserName&:&&},&platformVersion&:&7.1&,&app&:&io.appium.TestApp&,&platformName&:&iOS&,&deviceName&:&iPhone Simulator&},&sessionId&:&2bcd619b-b7fb-45f5-b20c-79caff8cd24f&}
..........
java真机运行的代码:
package com.saucelabs.
import static org.junit.Assert.assertT
import io.appium.java_client.AppiumD
import io.appium.java_client.MobileBy;
import java.net.URL;
import java.util.ArrayL
import java.util.L
import java.util.R
import org.junit.A
import org.junit.B
import org.junit.T
import org.openqa.selenium.By;
import org.openqa.selenium.D
import org.openqa.selenium.P
import org.openqa.selenium.WebE
import org.openqa.selenium.remote.CapabilityT
import org.openqa.selenium.remote.DesiredC
&* Simple &a href=&/appium/appium&&Appium&/a& test which runs
&* against a local Appium instance deployed with the 'TestApp' iPhone project
&* which is included in the Appium source distribution.
&* @author Ross Rowe
public class WiMyOffice {
& private AppiumDriver & &
& private List&Integer& & &
& private static final int MINIMUM = 0;
& private static final int MAXIMUM = 10;
& private Point getCenter(final WebElement element) {
& & final Point upperLeft = element.getLocation();
& & final Dimension dimensions = element.getSize();
& & return new Point(upperLeft.getX() + dimensions.getWidth() / 2,
& & & & upperLeft.getY() + dimensions.getHeight() / 2);
& private void populate() {
& & // populate text fields with two random number
& & final List&WebElement& elems = driver.findElements(By
& & & & .className(&UIATextField&));
& & final Random random = new Random();
& & for (final WebElement elem : elems) {
& & & final int rndNum = random.nextInt(MAXIMUM - MINIMUM + 1) + MINIMUM;
& & & elem.sendKeys(String.valueOf(rndNum));
& & & values.add(rndNum);
& public void setUp() throws Exception {
& & // set up appium
& & final DesiredCapabilities capabilities = new DesiredCapabilities();
& & capabilities.setCapability(CapabilityType.BROWSER_NAME, &&);
& & capabilities.setCapability(&platformVersion&, &7.1&);
& & capabilities.setCapability(&platformName&, &iOS&);
& & capabilities.setCapability(&deviceName&, &iPhone Simulator&);
& & capabilities.setCapability(&app&, &io.appium.TestApp&);
& & driver = new AppiumDriver(new URL(&http://127.0.0.1:4723/wd/hub&),
& & & & capabilities);
& & values = new ArrayList&Integer&();
& public void tearDown() throws Exception {
& & driver.quit();
& public void testHideKeyboard() throws Exception {
& & driver.findElement(By.xpath(&//UIATextField[1]&)).sendKeys(&12&);
& & final WebElement button = driver.findElement(MobileBy
& & & & .AccessibilityId(&Done&));
& & assertTrue(button.isDisplayed());
& & button.click();
java上在模拟器上跑的实例:
命令行输入:appium &启动服务就可以了
lsof -i:4723查看端口号有没有被占用,占用就用 kill -9 进程ID
package com.saucelabs.
import static org.junit.Assert.assertT
import io.appium.java_client.AppiumD
import java.io.F
import java.net.URL;
import java.util.ArrayL
import java.util.L
import java.util.R
import org.junit.A
import org.junit.B
import org.junit.T
import org.openqa.selenium.By;
import org.openqa.selenium.D
import org.openqa.selenium.P
import org.openqa.selenium.WebE
import org.openqa.selenium.remote.CapabilityT
import org.openqa.selenium.remote.DesiredC
&* Simple &a href=&/appium/appium&&Appium&/a& test which runs
&* against a local Appium instance deployed with the 'TestApp' iPhone project
&* which is included in the Appium source distribution.
&* @author Ross Rowe
public class SimpleTest {
& private AppiumDriver & &
& private List&Integer& & &
& private static final int MINIMUM = 0;
& private static final int MAXIMUM = 10;
& private Point getCenter(final WebElement element) {
& & final Point upperLeft = element.getLocation();
& & final Dimension dimensions = element.getSize();
& & return new Point(upperLeft.getX() + dimensions.getWidth() / 2,
& & & & upperLeft.getY() + dimensions.getHeight() / 2);
& private void populate() {
& & // populate text fields with two random number
& & final List&WebElement& elems = driver.findElements(By
& & & & .className(&UIATextField&));
& & final Random random = new Random();
& & for (final WebElement elem : elems) {
& & & final int rndNum = random.nextInt(MAXIMUM - MINIMUM + 1) + MINIMUM;
& & & elem.sendKeys(String.valueOf(rndNum));
& & & values.add(rndNum);
& public void setUp() throws Exception {
& & // set up appium
& & final File appDir = new File(System.getProperty(&user.dir&),
& & & & &../../../apps/TestApp/build/Release-iphonesimulator&);
& & final File app = new File(appDir, &TestApp.app&);
& & final DesiredCapabilities capabilities = new DesiredCapabilities();
& & capabilities.setCapability(CapabilityType.BROWSER_NAME, &&);
& & capabilities.setCapability(&platformVersion&, &7.1&);
& & capabilities.setCapability(&platformName&, &iOS&);
& & capabilities.setCapability(&deviceName&, &iPhone Simulator&);
& & capabilities.setCapability(&app&, app.getAbsolutePath());
& & driver = new AppiumDriver(new URL(&http://127.0.0.1:4723/wd/hub&),
& & & & capabilities);
& & values = new ArrayList&Integer&();
& public void tearDown() throws Exception {
& & driver.quit();
& public void testActive() throws Exception {
& & final WebElement text = driver.findElement(By.xpath(&//UIATextField[1]&));
& & assertTrue(text.isDisplayed());
& & final WebElement button = driver.findElement(By.xpath(&//UIAButton[1]&));
& & assertTrue(button.isDisplayed());
12345678910
12345678910
12345678910 上一篇:下一篇:文章评论相关解决方案 12345678910 Copyright & &&版权所有Appium Python API
Appium Python API(by appium 1.4.13.1)- .contextscontexts(self):
Returns the contexts within the current session.
返回当前会话中的上下文,使用后可以识别H5页面的控件
driver.contexts
用法 driver.contexts- . current_contextcurrent_context(self):Returns the current context of the current session.返回当前会话的当前上下文:Usage:
driver.current_context用法driver. current_context- . contextcontext(self):
Returns the current context of the current session.
返回当前会话的当前上下文。
driver.context用法driver. Context- . find_element_by_ios_uiautomationfind_element_by_ios_uiautomation(self, uia_string):Finds an element by uiautomation in iOS.
通过iOS uiautomation查找元素
- uia_string - The element name in the iOS UIAutomation library
driver.find_element_by_ios_uiautomation('.elements()[1].cells()[2]')用法dr. find_element_by_ios_uiautomation(‘elements’)-. find_element_by_accessibility_idfind_element_by_accessibility_id(self, id):Finds an element by accessibility id.
通过accessibility id查找元素
- id - a string corresponding to a recursive element search using the
Id/Name that the native Accessibility options utilize
driver.find_element_by_accessibility_id()用法driver.find_element_by_accessibility_id(‘id’)- .scrollscroll(self, origin_el, destination_el):Scrolls from one element to another
从元素origin_el滚动至元素destination_el
- originalEl - the element from which to being scrolling
- destinationEl - the element to scroll to
driver.scroll(el1, el2)用法 driver.scroll(el1,el2)- . drag_and_dropdrag_and_drop(self, origin_el, destination_el):Drag the origin element to the destination element
将元素origin_el拖到目标元素destination_el
- originEl - the element to drag
- destinationEl - the element to drag to用法 driver.drag_and_drop(el1,el2)- .taptap(self, positions, duration=None):Taps on an particular place with up to five fingers, holding for a certain time模拟手指点击(最多五个手指),可设置按住时间长度(毫秒)
- positions - an array of tuples representing the x/y coordinates of
the fingers to tap. Length can be up to five.
- duration - (optional) length of time to tap, in ms
driver.tap([(100, 20), (100, 60), (100, 100)], 500)用法 driver.tap([(x,y),(x1,y1)],500)- . swipeswipe(self, start_x, start_y, end_x, end_y, duration=None):Swipe from one point to another point, for an optional duration.
从A点滑动至B点,滑动时间为毫秒
- start_x - x-coordinate at which to start
- start_y - y-coordinate at which to start
- end_x - x-coordinate at which to stop
- end_y - y-coordinate at which to stop
- duration - (optional) time to take the swipe, in ms.
driver.swipe(100, 100, 100, 400)用法 driver.swipe(x1,y1,x2,y2,500)- .flickflick(self, start_x, start_y, end_x, end_y):Flick from one point to another point.
按住A点后快速滑动至B点
- start_x - x-coordinate at which to start
- start_y - y-coordinate at which to start
- end_x - x-coordinate at which to stop
- end_y - y-coordinate at which to stop
driver.flick(100, 100, 100, 400)用法 driver.flick(x1,y1,x2,y2)- .pinchpinch(self, element=None, percent=200, steps=50):Pinch on an element a certain amount
在元素上执行模拟双指捏(缩小操作)
- element - the element to pinch
- percent - (optional) amount to pinch. Defaults to 200%
- steps - (optional) number of steps in the pinch action
driver.pinch(element)用法 driver.pinch(element)- .zoomzoom(self, element=None, percent=200, steps=50):Zooms in on an element a certain amount
在元素上执行放大操作
- element - the element to zoom
- percent - (optional) amount to zoom. Defaults to 200%
- steps - (optional) number of steps in the zoom action
driver.zoom(element)用法 driver.zoom(element)- .resetreset(self):Resets the current application on the device.重置应用(类似删除应用数据)用法 driver.reset()14. hide_keyboardhide_keyboard(self, key_name=None, key=None, strategy=None):Hides the software keyboard on the device. In iOS, use `key_name` to press a particular key, or `strategy`. In Android, no parameters are used.
隐藏键盘,iOS使用key_name隐藏,安卓不使用参数
- key_name - key to press
- strategy - strategy for closing the keyboard (e.g., `tapOutside`)driver.hide_keyboard()- . keyeventkeyevent(self, keycode, metastate=None):Sends a keycode to the device. Android only. Possible keycodes can be found in /reference/android/view/KeyEvent.html.
发送按键码(安卓仅有),按键码可以上网址中找到
- keycode - the keycode to be sent to the device
- metastate - meta information about the keycode being sent用法 dr.keyevent(‘4’)16. press_keycodepress_keycode(self, keycode, metastate=None):Sends a keycode to the device. Android only. Possible keycodes can be found in /reference/android/view/KeyEvent.html.
发送按键码(安卓仅有),按键码可以上网址中找到
- keycode - the keycode to be sent to the device
- metastate - meta information about the keycode being sent用法 driver.press_ keycode(‘4’)dr.keyevent(‘4’)与driver.press_ keycode(‘4’) 功能实现上一样的,都是按了返回键- . long_press_keycodelong_press_keycode(self, keycode, metastate=None):Sends a long press of keycode to the device. Android only. Possible keycodes can be
found in /reference/android/view/KeyEvent.html.
发送一个长按的按键码(长按某键)
- keycode - the keycode to be sent to the device
- metastate - meta information about the keycode being sent 用法 driver.long_press_keycode(‘4’)- .current_activitycurrent_activity(self):Retrieves the current activity on the device.获取当前的activity用法 print(driver.current_activity())- . wait_activitywait_activity(self, activity, timeout, interval=1):Wait for an activity: block until target activity presents or time out.
This is an Android-only method.
等待指定的activity出现直到超时,interval为扫描间隔1秒即每隔几秒获取一次当前的activity返回的True 或 False
- activity - target activity
- timeout - max wait time, in seconds
- interval - sleep interval between retries, in seconds用法driver.wait_activity(‘.activity.xxx’,5,2)- . background_appbackground_app(self, seconds):Puts the application in the background on the device for a certain duration.
后台运行app多少秒
- seconds - the duration for the application to remain in the background用法 driver.background_app(5)
置后台5秒后再运行- .is_app_installedis_app_installed(self, bundle_id):Checks whether the application specified by `bundle_id` is installed on the device.
检查app是否有安装返回 True or False
- bundle_id - the id of the application to query用法 driver.is_app_installed(“com.xxxx”)- .install_appinstall_app(self, app_path):Install the application found at `app_path` on the device.
安装app,app_path为安装包路径
- app_path - the local or remote path to the application to install用法 driver.install_app(app_path)- .remove_appremove_app(self, app_id):Remove the specified application from the device.
- app_id - the application id to be removed用法 driver.remove_app(“com.xxx.”)- .launch_applaunch_app(self):Start on the device the application specified in the desired capabilities.启动app用法 driver.launch_app()- .close_appclose_app(self):Stop the running application, specified in the desired capabilities, on the device.关闭app用法 driver.close_app()启动和关闭app运行好像会出错- . start_activitystart_activity(self, app_package, app_activity, **opts):Opens an arbitrary activity during a test. If the activity belongs to
another application, that application is started and the activity is opened.
This is an Android-only method.
在测试过程中打开任意活动。如果活动属于另一个应用程序,该应用程序的启动和活动被打开。这是一个安卓的方法
- app_package - The package containing the activity to start.
- app_activity - The activity to start.
- app_wait_package - Begin automation after this package starts (optional).
- app_wait_activity - Begin automation after this activity starts (optional).
- intent_action - Intent to start (optional).
- intent_category - Intent category to start (optional).
- intent_flags - Flags to send to the intent (optional).
- optional_intent_arguments - Optional arguments to the intent (optional).
- stop_app_on_reset - Should the app be stopped on reset (optional)?用法 driver.start_activity(app_package, app_activity)- .locklock(self, seconds):Lock the device for a certain period of time. iOS only.
锁屏一段时间
- the duration to lock the device, in seconds用法 driver.lock()- .shakeshake(self):Shake the device.摇一摇手机用法 driver.shake()- .open_notificationsopen_notifications(self):Open notification shade in Android (API Level 18 and above)打系统通知栏(仅支持API 18 以上的安卓系统)用法 driver.open_notifications()- .network_connectionnetwork_connection(self):Returns an integer bitmask specifying the network connection type.
Android only.返回网络类型
Possible values are available through the enumeration `appium.webdriver.ConnectionType`用法 driver.network_connection- . set_network_connectionset_network_connection(self, connectionType):Sets the network connection type. Android only.
Possible values:
Value (Alias)
| Data | Wifi | Airplane Mode
-------------------------------------------------
1 (Airplane Mode)
2 (Wifi only)
4 (Data only)
6 (All network on) | 1
These are available through the enumeration `appium.webdriver.ConnectionType`
设置网络类型
- connectionType - a member of the enum appium.webdriver.ConnectionType用法
先加载from appium.webdriver.connectiontype import ConnectionTypedr.set_network_connection(ConnectionType.WIFI_ONLY)ConnectionType的类型有NO_CONNECTION = 0AIRPLANE_MODE = 1WIFI_ONLY = 2DATA_ONLY = 4ALL_NETWORK_ON = 6- . available_ime_enginesavailable_ime_engines(self):Get the available input methods for an Android device. Package and activity are returned (e.g., ['com.android.inputmethod.latin/.LatinIME'])
Android only.返回安卓设备可用的输入法用法print(driver.available_ime_engines)- .is_ime_activeis_ime_active(self):Checks whether the device has IME service active. Returns True/False.
Android only.检查设备是否有输入法服务活动。返回真/假。安卓用法 print(driver.is_ime_active())- .activate_ime_engineactivate_ime_engine(self, engine):Activates the given IME engine on the device.
Android only.
激活安卓设备中的指定输入法,设备可用输入法可以从“available_ime_engines”获取
- engine - the package and activity of the IME engine to activate (e.g.,
'com.android.inputmethod.latin/.LatinIME')用法 driver.activate_ime_engine(“com.android.inputmethod.latin/.LatinIME”)- .deactivate_ime_enginedeactivate_ime_engine(self):Deactivates the currently active IME engine on the device.
Android only.关闭安卓设备当前的输入法用法 driver.deactivate_ime_engine()- .active_ime_engineactive_ime_engine(self):Returns the activity and package of the currently active IME engine (e.g.,
'com.android.inputmethod.latin/.LatinIME').
Android only.
返回当前输入法的包名- . toggle_location_servicestoggle_location_services(self):Toggle the location services on the device. Android only.打开安卓设备上的位置定位设置用法 driver.toggle_location_services()38.set_locationset_location(self, latitude, longitude, altitude):Set the location of the device
设置设备的经纬度
- latitude纬度 - String or numeric value between -90.0 and 90.00
- longitude经度 - String or numeric value between -180.0 and 180.0
- altitude海拔高度- String or numeric value用法 driver.set_location(纬度,经度,高度)tag_name(self):This element's ``tagName`` property.返回元素的tagName属性经实践返回的是class name用法 element.tag_name()- .texttext(self):The text of the element.
返回元素的文本值用法 element.text()41.clickclick(self):Clicks the element.
点击元素用法 element.click()- .submitsubmit(self):Submits a form.
提交表单用法 暂无- .clearclear(self):Clears the text if it's a text entry element.
清除输入的内容用法 element.clear()- .get_attributeget_attribute(self, name):详见@chenhengjie123 的超级链接Gets the given attribute or property of the element.1、获取 content-desc 的方法为 get_attribute("name") ,而且还不能保证返回的一定是 content-desc (content-desc 为空时会返回 text 属性值)2、get_attribute 方法不是我们在 uiautomatorviewer 看到的所有属性都能获取的(此处的名称均为使用 get_attribute 时使用的属性名称):可获取的:字符串类型:name(返回 content-desc 或 text)text(返回 text)className(返回 class,只有 API=&18 才能支持)resourceId(返回 resource-id,只有 API=&18 才能支持)
This method will first try to return the value of a property with the
given name. If a property with that name doesn't exist, it returns the
value of the attribute with the same name. If there's no attribute with
that name, ``None`` is returned.
Values which are considered truthy, that is equals "true" or "false",
are returned as booleans.
All other non-``None`` values are returned
as strings.
For attributes or properties which do not exist, ``None``
is returned.
- name - Name of the attribute/property to retrieve.
# Check if the "active" CSS class is applied to an element.
is_active = "active" in target_element.get_attribute("class")用法:详见下一章- .is_selectedis_selected(self):Returns whether the element is selected.
Can be used to check if a checkbox or radio button is selected.返回元素是否选择。可以用来检查一个复选框或单选按钮被选中。用法 element.is_slected()- .is_enabledis_enabled(self):Returns whether the element is enabled.
返回元素是否可用True of False用法 element.is_enabled()- .find_element_by_idfind_element_by_id(self, id_):Finds element within this element's children by ID.
通过元素的ID定位元素
- id_ - ID of child element to locate.用法 driver. find_element_by_id(“id”)- . find_elements_by_idfind_elements_by_id(self, id_):Finds a list of elements within this element's children by ID.
通过元素ID定位,含有该属性的所有元素
- id_ - Id of child element to find.用法 driver. find_elements_by_id(“id”)- . find_element_by_namefind_element_by_name(self, name):Finds element within this element's children by name.
通过元素Name定位(元素的名称属性text)
- name - name property of the element to find.用法 driver.find_element_by_name(“name”)-. find_elements_by_namefind_elements_by_name(self, name):Finds a list of elements within this element's children by name.
通过元素Name定位(元素的名称属性text),含有该属性的所有元素
- name - name property to search for.用法 driver.find_element_by_name(“name”)- . find_element_by_link_textfind_element_by_link_text(self, link_text):Finds element within this element's children by visible link text.
通过元素可见链接文本定位
- link_text - Link text string to search for.用法 driver.find_element_by_link_text(“text”)- . find_elements_by_link_textfind_element_by_link_text(self, link_text): Finds a list of elements within this element's children by visible link text
通过元素可见链接文本定位,含有该属性的所有元素
- link_text - Link text string to search for.用法 driver.find_elements_by_link_text(“text”)- . find_element_by_partial_link_textfind_element_by_partial_link_text(self, link_text):Finds element within this element's children by partially visible link text.
通过元素部分可见链接文本定位
- link_text - Link text string to search for.driver. find_element_by_partial_link_text(“text”)- . find_elements_by_partial_link_textfind_elements_by_partial_link_text(self, link_text):Finds a list of elements within this element's children by link text.
通过元素部分可见链接文本定位,含有该属性的所有元素
- link_text - Link text string to search for.driver. find_elements_by_partial_link_text(“text”)find_element_by_tag_name(self, name):Finds element within this element's children by tag name.
通过查找html的标签名称定位元素
- name - name of html tag (eg: h1, a, span)用法
driver.find_element_by_tag_name(“name”)find_elements_by_tag_name(self, name):Finds a list of elements within this element's children by tag name.
通过查找html的标签名称定位所有元素
- name - name of html tag (eg: h1, a, span)用法driver.find_elements_by_tag_name(“name”)- . find_element_by_xpathfind_element_by_xpath(self, xpath):Finds element by xpath.
通过Xpath定位元素,详细方法可参阅.cn/xpath/
xpath - xpath of element to locate.
"//input[@class='myelement']"
Note: The base path will be relative to this element's location.
This will select the first link under this element.
myelement.find_elements_by_xpath(".//a")
However, this will select the first link on the page.
myelement.find_elements_by_xpath("//a")用法 find_element_by_xpath(“//*”)- . find_elements_by_xpathfind_elements_by_xpath(self, xpath):Finds elements within the element by xpath.
- xpath - xpath locator string.
Note: The base path will be relative to this element's location.
This will select all links under this element.
myelement.find_elements_by_xpath(".//a")
However, this will select all links in the page itself.
myelement.find_elements_by_xpath("//a")用法find_elements_by_xpath(“//*”)- . find_element_by_class_namefind_element_by_class_name(self, name):Finds element within this element's children by class name.
通过元素class name属性定位元素
- name - class name to search for.用法 driver. find_element_by_class_name(“android.widget.LinearLayout”)- . find_elements_by_class_namefind_elements_by_class_name(self, name):Finds a list of elements within this element's children by class name.
通过元素class name属性定位所有含有该属性的元素
- name - class name to search for.用法 driver. find_elements_by_class_name(“android.widget.LinearLayout”)- . find_element_by_css_selectorfind_element_by_css_selector(self, css_selector):Finds element within this element's children by CSS selector.
通过CSS选择器定位元素
- css_selector - CSS selctor string, ex: 'a.nav#home'- .send_keyssend_keys(self, *value):Simulates typing into the element.
在元素中模拟输入(开启appium自带的输入法并配置了appium输入法后,可以输入中英文)
- value - A string for typing, or setting form fields.
For setting
file inputs, this could be a local file path.
Use this to send simple key events or to fill out form fields::
form_textfield = driver.find_element_by_name('username')
form_textfield.send_keys("admin")
This can also be used to set file inputs.
file_input = driver.find_element_by_name('profilePic')
file_input.send_keys("path/to/profilepic.gif")
# Generally it's better to wrap the file path in one of the methods
# in os.path to return the actual path to support cross OS testing.
# file_input.send_keys(os.path.abspath("path/to/profilepic.gif"))driver.element.send_keys(“中英”)- . is_displayedis_displayed(self):Whether the element is visible to a user.
此元素用户是否可见。简单地说就是隐藏元素和被控件挡住无法操作的元素(仅限 Selenium,appium是否实现了类似功能不是太确定)这一项都会返回 False用法 driver.element.is_displayed()- . location_once_scrolled_into_viewlocation_once_scrolled_into_view(self): """THIS PROPERTY MAY CHANGE WITHOUT WARNING. Use this to discover
where on the screen an element is so that we can click it. This method
should cause the element to be scrolled into view.
Returns the top lefthand corner location on the screen, or ``None`` if
the element is not visible.
暂不知道用法
"""- .sizesize(self):The size of the element.获取元素的大小(高和宽)new_size["height"] = size["height"]new_size["width"] = size["width"]用法 driver.element.size- . value_of_css_propertyvalue_of_css_property(self, property_name):The value of a CSS property.CSS属性用法 暂不知- .locationlocation(self):The location of the element in the renderable canvas.
获取元素左上角的坐标用法 driver.element.location'''返回element的x坐标, int类型'''driver.element.location.get('x')'''返回element的y坐标, int类型'''driver.element.location.get('y')- .rectrect(self):A dictionary with the size and location of the element.
元素的大小和位置的字典- . screenshot_as_base64screenshot_as_base64(self):
Gets the screenshot of the current element as a base64 encoded string.
获取当前元素的截图为Base64编码的字符串
img_b64 = element.screenshot_as_base64- .execute_scriptexecute_script(self, script, *args):
Synchronously Executes JavaScript in the current window/frame.在当前窗口/框架(特指 Html 的 iframe )同步执行 javascript 代码。你可以理解为如果这段代码是睡眠5秒,这五秒内主线程的 javascript 不会执行
- script: The JavaScript to execute.
- /*args: Any applicable arguments for your JavaScript.
driver.execute_script('document.title')- .execute_async_scriptexecute_async_script(self, script, *args):
Asynchronously Executes JavaScript in the current window/frame.插入 javascript 代码,只是这个是异步的,也就是如果你的代码是睡眠5秒,那么你只是自己在睡,页面的其他 javascript 代码还是照常执行
- script: The JavaScript to execute.
- /*args: Any applicable arguments for your JavaScript.
driver.execute_async_script('document.title')- .current_urlcurrent_url(self):
Gets the URL of the current page.
获取当前页面的网址。
driver.current_url用法 driver.current_url- . page_sourcepage_source(self):
Gets the source of the current page.
获取当前页面的源。
driver.page_source- .closeclose(self):
Closes the current window.
关闭当前窗口
driver.close()- .quitquit(self):
Quits the driver and closes every associated window.
退出脚本运行并关闭每个相关的窗口连接
driver.quit()10 appium get_attribute 问题描述问题描述 当使用类似下面的代码获取元素的 content-desc 属性时,会报 NoSuchElement 错误:self.driver.find_element_by_id("id").get_attribute("content-desc")但使用如下代码却能正常执行:self.driver.find_element_by_id("id").click()很明显,这个错误原因不是找不到元素,而是 get_attribute 出问题。问题原因探究appium server 在 android 原生应用上获取 attribute 的大致流程为:从 client 收到获取 attribute 的请求把请求转发给在手机上运行的 bootstrapbootstrap 调用相关方法进行实际操作bootstrap 返回结果给 appium serverappium server 把结果返回给 client通过排查各部分的代码发现,错误是在 bootstrap 产生的(排查过程涉及代码有点多,所以这里就不解释了),所以看看 bootstrap 相关源码:lib/devices/android/bootstrap/src/io/appium/android/bootstrap/handler/GetAttribute.java@Override
public AndroidCommandResult execute(final AndroidCommand command)
throws JSONException {if (command.isElementCommand()) {
// only makes sense on an element
final Hashtable&String, Object& params = command.params();
try {// 获取需要操作的 element 实例final AndroidElement el = command.getElement();// 获取需要获取的 attribute 的名称final String attr = params.get("attribute").toString();if (attr.equals("name") || attr.equals("text")|| attr.equals("className") || attr.equals("resourceId")) {
// 如果 attribute 名称为 name, text, className, resourceId ,调用元素的 getStringAttribute 方法获取
return getSuccessResult(el.getStringAttribute(attr));} else {
// 否则调用 getBoolAttribute 获取 (我们的 'content-desc' 执行的是这段语句)
return getSuccessResult(String.valueOf(el.getBoolAttribute(attr)));}
} catch (final NoAttributeFoundException e) {// 从这里开始就是第一个坑,无论是什么错误,最终返回的都是 NO_SUCH_ELEMENTreturn new AndroidCommandResult(WDStatus.NO_SUCH_ELEMENT,e.getMessage());
} catch (final UiObjectNotFoundException e) {return new AndroidCommandResult(WDStatus.NO_SUCH_ELEMENT,e.getMessage());
} catch (final Exception e) { // el is nullreturn new AndroidCommandResult(WDStatus.NO_SUCH_ELEMENT,e.getMessage());
// 没有给出需要获取属性的 element ,返回错误信息
return getErrorResult("Unable to get attribute without an element.");}
}其中 getStringAttribute 和 getBoolAttribute 源码如下:lib/devices/android/bootstrap/src/io/appium/android/bootstrap/AndroidElement.javapublic String getStringAttribute(final String attr)
throws UiObjectNotFoundException, NoAttributeFoundException {
if (attr.equals("name")) {
// 坑2:属性名称为 name 时,会先尝试获取 content-desc ,如果 content-desc 为空,则获取 text 。说白了,就算用 name 也不能保证你获取的就是 content-desc
res = getContentDesc();
if (res.equals("")) {
res = getText();
} else if (attr.equals("text")) {
res = getText();
} else if (attr.equals("className")) {
res = getClassName();
} else if (attr.equals("resourceId")) {
res = getResourceId();
throw new NoAttributeFoundException(attr);
}...public boolean getBoolAttribute(final String attr)
throws UiObjectNotFoundException, NoAttributeFoundException {
// 这个方法只会获取值为布尔类型的属性,我们的 content-desc 的值不是布尔类型的,所以抛出 NoAttributeFoundException
if (attr.equals("enabled")) {
res = el.isEnabled();
} else if (attr.equals("checkable")) {
res = el.isCheckable();
} else if (attr.equals("checked")) {
res = el.isChecked();
} else if (attr.equals("clickable")) {
res = el.isClickable();
} else if (attr.equals("focusable")) {
res = el.isFocusable();
} else if (attr.equals("focused")) {
res = el.isFocused();
} else if (attr.equals("longClickable")) {
res = el.isLongClickable();
} else if (attr.equals("scrollable")) {
res = el.isScrollable();
} else if (attr.equals("selected")) {
res = el.isSelected();
} else if (attr.equals("displayed")) {
res = el.exists();
throw new NoAttributeFoundException(attr);
}总结1、获取 content-desc 的方法为 get_attribute(“name”) ,而且还不能保证返回的一定是 content-desc (content-desc 为空时会返回 text 属性值) 2、get_attribute 方法不是我们在 uiautomatorviewer 看到的所有属性都能获取的(此处的名称均为使用 get_attribute 时使用的属性名称):可获取的:字符串类型:name(返回 content-desc 或 text)text(返回 text)className(返回 class,只有 API=&18 才能支持)resourceId(返回 resource-id,只有 API=&18 才能支持)布尔类型(如果无特殊说明, get_attribute 里面使用的属性名称和 uiautomatorviewer 里面的一致):enabledcheckablecheckedclickablefocusablefocusedlongClickable(返回 long-clickable)scrollableselecteddisplayed(此元素是否在当前界面存在。调用的是 UIObject 的 exists() 方法,详情请看 /reference/android/support/test/uiautomator/UiObject.html#exists())* 获取不到,但会显示在 uiautomatorviewer 中的属性*:indexpackagepasswordbounds(可通过 get_position 来获取其中部分内容)
无相关信息
最新教程周点击榜
微信扫一扫}

我要回帖

更多关于 appium python脚本 的文章

更多推荐

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

点击添加站长微信