前言:
AppiumPythonAPI全集,不知道哪个大神整理的,这里贴出来分享给大家。
contexts(self):
Returnsthecontextswithinthecurrentsession.
返回当前会话中的上下文,使用后可以识别H5页面的控件
:Usage:
driver.contexts
用法driver.contexts
current_context(self):
Returnsthecurrentcontextofthecurrentsession.
返回当前会话的当前上下文
:Usage:
driver.current_context
用法driver.current_context
context(self):
Returnsthecurrentcontextofthecurrentsession.
返回当前会话的当前上下文。
:Usage:
driver.context
用法driver.Context
find_element_by_ios_uiautomation(self,uia_string):
FindsanelementbyuiautomationiniOS.
通过iOSuiautomation查找元素
:Args:
-uia_string-TheelementnameintheiOSUIAutomationlibrary
:Usage:
driver.find_element_by_ios_uiautomation(.elements()[1].cells()[2])
用法dr.find_element_by_ios_uiautomation(‘elements’)
find_element_by_accessibility_id(self,id):
Findsanelementbyaccessibilityid.
通过accessibilityid查找元素
:Args:
-id-astringcorrespondingtoarecursiveelementsearchusingthe
Id/NamethatthenativeAccessibilityoptionsutilize
:Usage:
driver.find_element_by_accessibility_id()
用法driver.find_element_by_accessibility_id(‘id’)
scroll(self,origin_el,destination_el):
Scrollsfromoneelementtoanother
从元素origin_el滚动至元素destination_el
:Args:
-originalEl-theelementfromwhichtobeingscrolling
-destinationEl-theelementtoscrollto
:Usage:
driver.scroll(el1,el2)
用法driver.scroll(el1,el2)
drag_and_drop(self,origin_el,destination_el):
Dragtheoriginelementtothedestinationelement
将元素origin_el拖到目标元素destination_el
:Args:
-originEl-theelementtodrag
-destinationEl-theelementtodragto
用法driver.drag_and_drop(el1,el2)
tap(self,positions,duration=None):
Tapsonanparticularplacewithuptofivefingers,holdingforacertaintime
模拟手指点击(最多五个手指),可设置按住时间长度(毫秒)
:Args:
-positions-anarrayoftuplesrepresentingthex/ycoordinatesof
thefingerstotap.Lengthcanbeuptofive.
-duration-(optional)lengthoftimetotap,inms
:Usage:
driver.tap([(100,20),(100,60),(100,100)],500)
用法driver.tap([(x,y),(x1,y1)],500)
swipe(self,start_x,start_y,end_x,end_y,duration=None):
Swipefromonepointtoanotherpoint,foranoptionalduration.
从A点滑动至B点,滑动时间为毫秒
:Args:
-start_x-x-coordinateatwhichtostart
-start_y-y-coordinateatwhichtostart
-end_x-x-coordinateatwhichtostop
-end_y-y-coordinateatwhichtostop
-duration-(optional)timetotaketheswipe,inms.
:Usage:
driver.swipe(100,100,100,400)
用法driver.swipe(x1,y1,x2,y2,500)
flick(self,start_x,start_y,end_x,end_y):
Flickfromonepointtoanotherpoint.
按住A点后快速滑动至B点
:Args:
-start_x-x-coordinateatwhichtostart
-start_y-y-coordinateatwhichtostart
-end_x-x-coordinateatwhichtostop
-end_y-y-coordinateatwhichtostop
:Usage:
driver.flick(100,100,100,400)
用法driver.flick(x1,y1,x2,y2)
pinch(self,element=None,percent=200,steps=50):
Pinchonanelementacertainamount
在元素上执行模拟双指捏(缩小操作)
:Args:
-element-theelementtopinch
-percent-(optional)amounttopinch.Defaultsto200%
-steps-(optional)numberofstepsinthepinchaction
:Usage:
driver.pinch(element)
用法driver.pinch(element)
zoom(self,element=None,percent=200,steps=50):
Zoomsinonanelementacertainamount
在元素上执行放大操作
:Args:
-element-theelementtozoom
-percent-(optional)amounttozoom.Defaultsto200%
-steps-(optional)numberofstepsinthezoomaction
:Usage:
driver.zoom(element)
用法driver.zoom(element)
reset(self):
Resetsthecurrentapplicationonthedevice.
重置应用(类似删除应用数据)
用法driver.reset()
hide_keyboardhide_keyboard(self,key_name=None,key=None,strategy=None):
Hidesthesoftwarekeyboardonthedevice.IniOS,use`key_name`topressaparticularkey,or`strategy`.InAndroid,noparametersareused.
隐藏键盘,iOS使用key_name隐藏,安卓不使用参数
:Args:
-key_name-keytopress
-strategy-strategyforclosingthekeyboard(e.g.,`tapOutside`)
driver.hide_keyboard()
keyevent(self,keycode,metastate=None):
Sendsakeycodetothedevice.Androidonly.Possiblekeycodescanbefoundinhttp://developer.android.com/reference/android/view/KeyEvent.html.
发送按键码(安卓仅有),按键码可以上网址中找到
:Args:
-keycode-thekeycodetobesenttothedevice
-metastate-metainformationaboutthekeycodebeingsent
用法dr.keyevent(‘4’)
press_keycode(self,keycode,metastate=None):
Sendsakeycodetothedevice.Androidonly.Possiblekeycodescanbefoundinhttp://developer.android.com/reference/android/view/KeyEvent.html.
发送按键码(安卓仅有),按键码可以上网址中找到
:Args:
-keycode-thekeycodetobesenttothedevice
-metastate-metainformationaboutthekeycodebeingsent
用法driver.press_keycode(‘4’)
dr.keyevent(‘4’)与driver.press_keycode(‘4’)功能实现上一样的,都是按了返回键
long_press_keycode(self,keycode,metastate=None):
Sendsalongpressofkeycodetothedevice.Androidonly.Possiblekeycodescanbe
foundinhttp://developer.android.com/reference/android/view/KeyEvent.html.
发送一个长按的按键码(长按某键)
:Args:
-keycode-thekeycodetobesenttothedevice
-metastate-metainformationaboutthekeycodebeingsent
用法driver.long_press_keycode(‘4’)
18.current_activity
current_activity(self):
Retrievesthecurrentactivityonthedevice.
获取当前的activity
用法print(driver.current_activity())
wait_activity(self,activity,timeout,interval=1):
Waitforanactivity:blockuntiltargetactivitypresentsortimeout.
ThisisanAndroid-onlymethod.
等待指定的activity出现直到超时,interval为扫描间隔1秒
即每隔几秒获取一次当前的activity
返回的True或False
:Agrs:
-activity-targetactivity
-timeout-maxwaittime,inseconds
-interval-sleepintervalbetweenretries,inseconds
用法driver.wait_activity(‘.activity.xxx’,5,2)
background_app(self,seconds):
Putstheapplicationinthebackgroundonthedeviceforacertainduration.
后台运行app多少秒
:Args:
-seconds-thedurationfortheapplicationtoremaininthebackground
用法driver.background_app(5)置后台5秒后再运行
is_app_installed(self,bundle_id):
Checkswhethertheapplicationspecifiedby`bundle_id`isinstalledonthedevice.
检查app是否有安装
返回TrueorFalse
:Args:
-bundle_id-theidoftheapplicationtoquery
用法driver.is_app_installed(“com.xxxx”)
install_app(self,app_path):
Installtheapplicationfoundat`app_path`onthedevice.
安装app,app_path为安装包路径
:Args:
-app_path-thelocalorremotepathtotheapplicationtoinstall
用法driver.install_app(app_path)
remove_app(self,app_id):
Removethespecifiedapplicationfromthedevice.
删除app
:Args:
-app_id-theapplicationidtoberemoved
用法driver.remove_app(“com.xxx.”)
launch_app(self):
Startonthedevicetheapplicationspecifiedinthedesiredcapabilities.
启动app
用法driver.launch_app()
close_app(self):
Stoptherunningapplication,specifiedinthedesiredcapabilities,onthedevice.
关闭app
用法driver.close_app()
启动和关闭app运行好像会出错
start_activity(self,app_package,app_activity,**opts):
Opensanarbitraryactivityduringatest.Iftheactivitybelongsto
anotherapplication,thatapplicationisstartedandtheactivityisopened.
ThisisanAndroid-onlymethod.
在测试过程中打开任意活动。如果活动属于另一个应用程序,该应用程序的启动和活动被打开。
这是一个安卓的方法
:Args:
-app_package-Thepackagecontainingtheactivitytostart.
-app_activity-Theactivitytostart.
-app_wait_package-Beginautomationafterthispackagestarts(optional).
-app_wait_activity-Beginautomationafterthisactivitystarts(optional).
-intent_action-Intenttostart(optional).
-intent_category-Intentcategorytostart(optional).
-intent_flags-Flagstosendtotheintent(optional).
-optional_intent_arguments-Optionalargumentstotheintent(optional).
-stop_app_on_reset-Shouldtheappbestoppedonreset(optional)?
用法driver.start_activity(app_package,app_activity)
lock(self,seconds):
Lockthedeviceforacertainperiodoftime.iOSonly.
锁屏一段时间iOS专有
:Args:
-thedurationtolockthedevice,inseconds
用法driver.lock()
28.shake
shake(self):
Shakethedevice.
摇一摇手机
用法driver.shake()
open_notifications(self):
OpennotificationshadeinAndroid(APILevel18andabove)
打系统通知栏(仅支持API18以上的安卓系统)
用法driver.open_notifications()
network_connection(self):
Returnsanintegerbitmaskspecifyingthenetworkconnectiontype.
Androidonly.
返回网络类型数值
Possiblevaluesareavailablethroughtheenumeration`appium.webdriver.ConnectionType`
用法driver.network_connection
set_network_connection(self,connectionType):
Setsthenetworkconnectiontype.Androidonly.
Possiblevalues:
Value(Alias)|Data|Wifi|AirplaneMode
-------------------------------------------------
0(None)|0|0|0
1(AirplaneMode)|0|0|1
2(Wifionly)|0|1|0
4(Dataonly)|1|0|0
6(Allnetworkon)|1|1|0
Theseareavailablethroughtheenumerationappium.webdriver.ConnectionType`
设置网络类型
:Args:
-connectionType-amemberoftheenumappium.webdriver.ConnectionType
用法先加载fromappium.webdriver.connectiontypeimportConnectionType
dr.set_network_connection(ConnectionType.WIFI_ONLY)
ConnectionType的类型有
NO_CONNECTION=0
AIRPLANE_MODE=1
WIFI_ONLY=2
DATA_ONLY=4
ALL_NETWORK_ON=6
available_ime_engines(self):
GettheavailableinputmethodsforanAndroiddevice.Packageandactivityarereturned(e.g.,[com.android.inputmethod.latin/.LatinIME])
Androidonly.
返回安卓设备可用的输入法
用法print(driver.available_ime_engines)
is_ime_active(self):
CheckswhetherthedevicehasIMEserviceactive.ReturnsTrue/False.
Androidonly.
检查设备是否有输入法服务活动。返回真/假。
安卓
用法print(driver.is_ime_active())
activate_ime_engine(self,engine):
ActivatesthegivenIMEengineonthedevice.
Androidonly.
激活安卓设备中的指定输入法,设备可用输入法可以从“available_ime_engines”获取
:Args:
-engine-thepackageandactivityoftheIMEenginetoactivate(e.g.,
com.android.inputmethod.latin/.LatinIME)
用法driver.activate_ime_engine(“com.android.inputmethod.latin/.LatinIME”)
deactivate_ime_engine(self):
DeactivatesthecurrentlyactiveIMEengineonthedevice.
Androidonly.
关闭安卓设备当前的输入法
用法driver.deactivate_ime_engine()
active_ime_engine(self):
ReturnstheactivityandpackageofthecurrentlyactiveIMEengine(e.g.,
com.android.inputmethod.latin/.LatinIME).
Androidonly.
返回当前输入法的包名
用法driver.active_ime_engine
toggle_location_services(self):
Togglethelocationservicesonthedevice.Androidonly.
打开安卓设备上的位置定位设置
用法driver.toggle_location_services()
set_location(self,latitude,longitude,altitude):
Setthelocationofthedevice
设置设备的经纬度
:Args:
-latitude纬度-Stringornumericvaluebetween-90.0and90.00
-longitude经度-Stringornumericvaluebetween-180.0and180.0
-altitude海拔高度-Stringornumericvalue
用法driver.set_location(纬度,经度,高度)
tag_name(self):
Thiselements``tagName``property.
返回元素的tagName属性
经实践返回的是classname
用法element.tag_name()
text(self):
Thetextoftheelement.
返回元素的文本值
用法element.text()
click(self):
Clickstheelement.
点击元素
用法element.click()
submit(self):
Submitsaform.
提交表单
用法暂无
clear(self):
Clearsthetextifitsatextentryelement.
清除输入的内容
用法element.clear()
get_attribute(self,name):
详见@chenhengjie123的超级链接
Getsthegivenattributeorpropertyoftheelement.
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才能支持)
Thismethodwillfirsttrytoreturnthevalueofapropertywiththe
givenname.Ifapropertywiththatnamedoesntexist,itreturnsthe
valueoftheattributewiththesamename.Iftheresnoattributewith
thatname,``None``isreturned.
Valueswhichareconsideredtruthy,thatisequals"true"or"false",
arereturnedasbooleans.Allothernon-``None``valuesarereturned
asstrings.Forattributesorpropertieswhichdonotexist,``None``
isreturned.
:Args:
-name-Nameoftheattribute/propertytoretrieve.
Example::
#Checkifthe"active"CSSclassisappliedtoanelement.
is_active="active"intarget_element.get_attribute("class")
用法暂无
is_selected(self):
Returnswhethertheelementisselected.
Canbeusedtocheckifacheckboxorradiobuttonisselected.
返回元素是否选择。
可以用来检查一个复选框或单选按钮被选中。
用法element.is_slected()
is_enabled(self):
Returnswhethertheelementisenabled.
返回元素是否可用TrueofFalse
用法element.is_enabled()
find_element_by_id(self,id_):
FindselementwithinthiselementschildrenbyID.
通过元素的ID定位元素
:Args:
-id_-IDofchildelementtolocate.
用法driver.find_element_by_id(“id”)
find_elements_by_id(self,id_):
FindsalistofelementswithinthiselementschildrenbyID.
通过元素ID定位,含有该属性的所有元素
:Args:
-id_-Idofchildelementtofind.
用法driver.find_elements_by_id(“id”)
find_element_by_name(self,name):
Findselementwithinthiselementschildrenbyname.
通过元素Name定位(元素的名称属性text)
:Args:
-name-namepropertyoftheelementtofind.
用法driver.find_element_by_name(“name”)
find_elements_by_name(self,name):
Findsalistofelementswithinthiselementschildrenbyname.
通过元素Name定位(元素的名称属性text),含有该属性的所有元素
:Args:
-name-namepropertytosearchfor.
用法driver.find_element_by_name(“name”)
find_element_by_link_text(self,link_text):
Findselementwithinthiselementschildrenbyvisiblelinktext.
通过元素可见链接文本定位
:Args:
-link_text-Linktextstringtosearchfor.
用法driver.find_element_by_link_text(“text”)
find_element_by_link_text(self,link_text):
Findsalistofelementswithinthiselementschildrenbyvisiblelinktext
通过元素可见链接文本定位,含有该属性的所有元素
:Args:
-link_text-Linktextstringtosearchfor.
用法driver.find_elements_by_link_text(“text”)
find_element_by_partial_link_text(self,link_text):
Findselementwithinthiselementschildrenbypartiallyvisiblelinktext.
通过元素部分可见链接文本定位
:Args:
-link_text-Linktextstringtosearchfor.
driver.find_element_by_partial_link_text(“text”)
find_elements_by_partial_link_text(self,link_text):
Findsalistofelementswithinthiselementschildrenbylinktext.
通过元素部分可见链接文本定位,含有该属性的所有元素
:Args:
-link_text-Linktextstringtosearchfor.
driver.find_elements_by_partial_link_text(“text”)
find_element_by_tag_name(self,name):
Findselementwithinthiselementschildrenbytagname.
通过查找html的标签名称定位元素
:Args:
-name-nameofhtmltag(eg:h1,a,span)
用法driver.find_element_by_tag_name(“name”)
find_elements_by_tag_name(self,name):
Findsalistofelementswithinthiselementschildrenbytagname.
通过查找html的标签名称定位所有元素
:Args:
-name-nameofhtmltag(eg:h1,a,span)
用法driver.find_elements_by_tag_name(“name”)
find_element_by_xpath(self,xpath):
Findselementbyxpath.
通过Xpath定位元素,详细方法可参阅http://www.w3school.com.cn/xpath/
:Args:
xpath-xpathofelementtolocate."//input[@class=myelement]"
Note:Thebasepathwillberelativetothiselementslocation.
Thiswillselectthefirstlinkunderthiselement.
::
myelement.find_elements_by_xpath(".//a")
However,thiswillselectthefirstlinkonthepage.
::
myelement.find_elements_by_xpath("//a")
用法find_element_by_xpath(“//*”)
find_elements_by_xpath(self,xpath):
Findselementswithintheelementbyxpath.
:Args:
-xpath-xpathlocatorstring.
Note:Thebasepathwillberelativetothiselementslocation.
Thiswillselectalllinksunderthiselement.
::
myelement.find_elements_by_xpath(".//a")
However,thiswillselectalllinksinthepageitself.
::
myelement.find_elements_by_xpath("//a")
用法find_elements_by_xpath(“//*”)
find_element_by_class_name(self,name):
Findselementwithinthiselementschildrenbyclassname.
通过元素classname属性定位元素
:Args:
-name-classnametosearchfor.
用法driver.find_element_by_class_name(“android.widget.LinearLayout”)
find_elements_by_class_name(self,name):
Findsalistofelementswithinthiselementschildrenbyclassname.
通过元素classname属性定位所有含有该属性的元素
:Args:
-name-classnametosearchfor.
用法driver.find_elements_by_class_name(“android.widget.LinearLayout”)
find_element_by_css_selector(self,css_selector):
FindselementwithinthiselementschildrenbyCSSselector.
通过CSS选择器定位元素
:Args:
-css_selector-CSSselctorstring,ex:a.nav#home
send_keys(self,*value):
Simulatestypingintotheelement.
在元素中模拟输入(开启appium自带的输入法并配置了appium输入法后,可以输入中英文)
:Args:
-value-Astringfortyping,orsettingformfields.Forsetting
fileinputs,thiscouldbealocalfilepath.
Usethistosendsimplekeyeventsortofilloutformfields::
form_textfield=driver.find_element_by_name(username)
form_textfield.send_keys("admin")
Thiscanalsobeusedtosetfileinputs.
::
file_input=driver.find_element_by_name(profilePic)
file_input.send_keys("path/to/profilepic.gif")
#Generallyitsbettertowrapthefilepathinoneofthemethods
#inos.pathtoreturntheactualpathtosupportcrossOStesting.
#file_input.send_keys(os.path.abspath("path/to/profilepic.gif"))
driver.element.send_keys(“中英”)
is_displayed(self):
Whethertheelementisvisibletoauser.
此元素用户是否可见。简单地说就是隐藏元素和被控件挡住无法操作的元素(仅限Selenium,appium是否实现了类似功能不是太确定)这一项都会返回False
用法driver.element.is_displayed()
location_once_scrolled_into_view(self):
"""THISPROPERTYMAYCHANGEWITHOUTWARNING.Usethistodiscover
whereonthescreenanelementissothatwecanclickit.Thismethod
shouldcausetheelementtobescrolledintoview.
Returnsthetoplefthandcornerlocationonthescreen,or``None``if
theelementisnotvisible.
暂不知道用法
"""
size(self):
Thesizeoftheelement.
获取元素的大小(高和宽)
new_size["height"]=size["height"]
new_size["width"]=size["width"]
用法driver.element.size
value_of_css_property(self,property_name):
ThevalueofaCSSproperty.
CSS属性
用法暂不知
location(self):
Thelocationoftheelementintherenderablecanvas.
获取元素左上角的坐标
用法driver.element.location
返回element的x坐标,int类型
driver.element.location.get(x)
返回element的y坐标,int类型
driver.element.location.get(y)
rect(self):
Adictionarywiththesizeandlocationoftheelement.
元素的大小和位置的字典
screenshot_as_base64(self):
Getsthescreenshotofthecurrentelementasabase64encodedstring.
获取当前元素的截图为Base64编码的字符串
:Usage:
img_b64=element.screenshot_as_base64
execute_script(self,script,*args):
SynchronouslyExecutesJavaScriptinthecurrentwindow/frame.
在当前窗口/框架(特指Html的iframe)同步执行javascript代码。你可以理解为如果这段代码是睡眠5秒,这五秒内主线程的javascript不会执行
:Args:
-script:TheJavaScripttoexecute.
-\*args:AnyapplicableargumentsforyourJavaScript.
:Usage:
driver.execute_script(document.title)
execute_async_script(self,script,*args):
AsynchronouslyExecutesJavaScriptinthecurrentwindow/frame.
插入javascript代码,只是这个是异步的,也就是如果你的代码是睡眠5秒,那么你只是自己在睡,页面的其他javascript代码还是照常执行
:Args:
-script:TheJavaScripttoexecute.
-\*args:AnyapplicableargumentsforyourJavaScript.
:Usage:
driver.execute_async_script(document.title)
current_url(self):
GetstheURLofthecurrentpage.
获取当前页面的网址。
:Usage:
driver.current_url
用法driver.current_url
page_source(self):
Getsthesourceofthecurrentpage.
获取当前页面的源。
:Usage:
driver.page_source
close(self):
Closesthecurrentwindow.
关闭当前窗口
:Usage:
driver.close()
quit(self):
Quitsthedriverandcloseseveryassociatedwindow.
退出脚本运行并关闭每个相关的窗口连接
:Usage:
driver.quit()
在学习过程中有遇到疑问的,可以加appium+pythonQQ群交流:330467341
word版的,在群附件也可以下载到
本文内容总结:1.contexts,2.current_context,3.context,4.find_element_by_ios_uiautomation,5.find_element_by_accessibility_id,6.scroll,7.drag_and_drop,8.tap,9.swipe,10.flick,11.pinch,12.zoom,13.reset,15.keyevent,16.press_keycode,17.long_press_keycode,19.wait_activity,20.background_app,21.is_app_installed,22.install_app,23.remove_app,24.launch_app,25.close_app,26.start_activity,27.lock,29.open_notifications,30.network_connection,31.set_network_connection,32.available_ime_engines,33.is_ime_active,34.activate_ime_engine,35.deactivate_ime_engine,36.active_ime_engine,37.toggle_location_services,38.set_location,39.tag_name,40.text,41.click,42.submit,43.clear,44.get_attribute,45.is_selected,46.is_enabled,47.find_element_by_id,48.find_elements_by_id,49.find_element_by_name,50.find_elements_by_name,51.find_element_by_link_text,52.find_elements_by_link_text,53.find_element_by_partial_link_text,54.find_elements_by_partial_link_text,55.find_element_by_tag_name,56.find_elements_by_tag_name,57.find_element_by_xpath,58.find_elements_by_xpath,59.find_element_by_class_name,60.find_elements_by_class_name,61.find_element_by_css_selector,62.send_keys,63.is_displayed,64.location_once_scrolled_into_view,65.size,66.value_of_css_property,67.location,68.rect,69.screenshot_as_base64,70.execute_script,71.execute_async_script,72.current_url,73.page_source,74.close,75.quit,
原文链接:https://www.cnblogs.com/yoyoketang/p/6189441.html