Source: Internet
Author: User
Tags unique id xpath appium

(1) Get the activity name of the current page, for example: (. ui.login.ViewPage)

current_activity ()

For example, we need to implement this login function, the main idea is that if the current interface is the login page, the login behavior, or jump to the login page. Its pseudo-code is:

1 if driver.current_activity = = ". Ui.login.ViewPage": 2     //To Login_action3 else:4     //Trun to LoginPage

(2) Get the tree structure source code of the current page, and the structure that the Uiautomatorviewer screenshot shows is the same

Page_source ()

For example, after we have completed the login process, to determine whether the login is successful, you can determine the login page has no specific content (such as: Sports Circle, Discovery, movement, Mall, my), its pseudo-code implementation is as follows:

Driver \     page_source.find (U "motion ring")! =-1 and     . Page_source.find (U "discover")! =-1 and     . Page_source.find (U "Motion")! =-1     and. Page_source.find (U "Mall")! =-1    and. Page_source.find (U "my")! =-1 and

The return data type of Page_source () is str. In Python, the Find (context) method of STR, if STR exists, the context return value is context at index of STR, and if not present, the return value is-1. So just to determine whether the Boolean value returned by the above code block is True or False, you can determine if the login was successful.

(3) Gets the name of all the context to the current window

contexts ()

In the native and HTML5 hybrid page tests, you need to switch between the native layer and the H5 layer, so you first need to get the name of the context hierarchy

Print Driver.contexts
>>> [' Native_app ', ' WEBVIEW_com.codoon.gps ']

Thus, we know that the H5 layer name of the app is "WEBVIEW_com.codoon.gps" and use Driver.switch_to.context ("WEBVIEW_com.codoon.gps") You can implement the native and H5 layers of the switch.

Second, get the control class API

(1) Find a target element of the current page by element ID

find_element_by_id ()

There are two main ways to get an API for find_element_by_id by using source annotations:

driver.find_element_by_id ("Com.codoon.gps:id/tv_login")  //from

Find an element by ID under driver, this usage usually applies to the driver of the current interface and only has a unique ID element, by calling find_element_by_id can be accurate to find the target element, another way to use the main is as follows:

Driver_element = Driver.find_element_by_xpath ("//android.widget.listview/android.widget.linearlayout")


driver_element.find_element_by_id ("Com.codoon.gps:id/activity_active_state")

When Driver.find_element_by_xpath returns the Driverelement type, the child element under Driverelement is called find_element_by_id to match the target element with an ID.

An illustration of Uiautomatorviewer to Id,name,class. Special NOTE: If the target element, such as ID, name, XPath, and so on, is not the only element in the current driver or Driverelement lookup, when find_element_by_id (Name\xpath) is called, the first element to find matches is returned.

(2) Find multiple target elements of the current page by element ID

find_elements_by_id ()

Find multiple target elements by ID under driver, whose return value type is list. This usage usually applies to item with the same layout structure as the ListView, LinearLayout, Relativelayout, and so on under the current driver, and in addition to driver, you can skip driverelement on the next page find_ elements_by_id to match the ListView, LinearLayout, Relativelayout.

driver.find_elements_by_id ("Com.codoon.gps:id/tv_name")  //from

. find_elements_by_id ("Com.codoon.gps:id/ll_layout") //from

Tips: The return type of a method function with the Find_elements keyword is a list data type, only driver and driverelement are instantiated with a series of methods such as find_element (s), and the list type is not available Find_ Element (s) method to locate the data. In the actual project you may encounter such problems, only traversing the list, take out each element instantiation object and then find the positioning element.

(3) Find an element of the current page by the element name

Find_element_by_name ()

Use the same way as find_element_by_id, just change the match condition from ID to name. Please refer to Find_element_by_id's Calling method

Driver.find_element_by_name ("foo") driver.find_element_by_id ("Com.codoon.gps:id/tv_name"). Find_element_by_name ( "Foo")

>>> return the driverelement (obj)

(4) Find multiple target elements of the current page by element name

Find_elements_by_name ()

Use the same way as find_elements_by_id, just change the match condition from ID to name. Please refer to Find_elements_by_id's invocation method, note that its return data type is list, not driverelement.

Driver.find_elements_by_name ("foo") driver.find_element_by_id ("Com.codoon.gps:id/tv_name"). Find_elements_by_ Name ("foo") # # #  return the list<driverelement>>>> [' driverElement1 ', ' driverElement2 ', ' DriverElement3 ', .....]

(5) Find a target element of the current page by element XPath

Find_element_by_xpath ()

Regarding the Find_element_by_xpath call method and through the ID, name slightly different, related to XPath knowledge points in this chapter is not table, follow-up in the project practice if there is a need for another presentation.

Driver.find_element_by_xpath ("//android.widget.textview[contains (@text, ' start ')]") Driver.find_element_by_xpath ("/ /android.widget.linearlayout/android.widget.textview ")

In Appium, the associated Lib libraries required for XPath are not fully supported, so the methods used are the above two (that is, only XPath matching under driver is supported). The current version of Appium does not support XPath lookups under Driverelement, such as

. Find_element_by_xpath ("//android.widget.textview[contains (@text, ' start ')]") //This is the error!

According to the above wording Appium will be an error, the reason is ". Find_element_by_xpath ("//android.widget.textview[contains (@text, ' start ')] ") You cannot find child elements under element.

(6) Find multiple target elements of the current page by element XPath

Find_elements_by_xpath ()

Referring to the invocation of Find_element_by_xpath, note that the return type is list, use reference find_elements_by_name () example

(7) Find an element of the current page by the element class name

Find_element_by_class_name ()

In the actual project, the test app in the class name does not serve as the unique location of the interface, so in practice almost no use of the class name in the driver view element, under Driverelement to find the child element with class name is the correct way to use.

(8) Find an element of the current page by Element accessibility_id (CONTENT-DESC)

find_element_by_accessibility_id ()

In Uiautomatorviewer, Content-desc content is accessibility_id, and find_element_by_name () can be used to match content-desc content in the Selenium library In the Appium Library, find_element_by_accessibility_id () is used to match the contents of the Content-desc. Because Appium inherits the Selenium class, try find_element_by_accessibility_id if find_element_by_name can't locate it correctly.

The commonly used get control class API is the above. Other search and Match APIs are find_element_by_link_text, Find_elements_by_link_text, Find_element_by_tag_name, Find_elements_by_ Tag_name, Find_element_by_css_selector, find_elements_by_css_selector, etc., use similar to the above.

Third, element operation class API

When we implement the PC-side browser Webdriver Automation, the main actions for the target on the webpage are: Click, double-click (Double_click), scroll (scroll), input (Send_keys), And the mobile-specific auxiliary class API: Tap--support multi-touch, swipe (swipe), magnify elements (pinch), Zoom Out (zoom)

(1) Click event

Click ()Tap ()

Click and tap all have the effect of clicking. The difference is that click is an instantiated object that acts on the driverelement, and tap is a click on the coordinate position on the screen. The former is not sensitive to the position change of the element, while the latter is for the specific pixel coordinate click, which is affected by the resolution and the element position.

(2) Input event

Send_keys ()Set_text ()

Send_keys and Set_text can also be adapted to the input text content. The difference is that Send_keys invokes the device's current system input keyboard, and set_text directly sets the text for the target element. As a result, the input content of Send_keys is often inconsistent with the expected content, while the input of Set_text is a direct assignment, not a keyboard event.

(3) Slide (flip screen) event

Swipe ()flick ()

Swipe and flick are all sliding operations, they are from [start_x, start_y] to [end_x, end_y] process, the only difference is swipe more than flick a duration parameter, With this parameter, you can customize the action time from start to end to achieve fast sliding or slow sliding effects.

(4) Scaling events

pinch ()Zoom ()

The default is to zoom in or out by one or half of the target elements, and this API method is appropriate for changing when you test the zoom of a motion map.

(5) Long press event

long_press ()

The long-press method is in the Touchaction class, so you need to import touchaction first when you use it. When you delete a motion history, long press DELETE in the record list,

Action1 = Touchaction (self.driver) driver_element = Driver.find_element_by_xpath ("Sport_history_item_xpath") Action1.long_press (driver_element). Wait (i *). Perform ()   //I is long press the control's time, unit seconds

(6) KeyEvent event (Android only)

In the Android KeyEvent event, different values represent different meanings and functions, such as the return key of the phone: keyevent (4); Phone's home key: KeyEvent (3), etc., the specific keyevent and corresponding value of the relationship, please refer to

Iv. element event class API

(1) Reset

Reset ()

Usage: Driver.reset (), resetting the app ( similar to deleting app data ), such as the boot page that appears when you first sign in to the app, you can use reset to implement your requirements.

(2) is_app_installed

is_app_installed ()

Check if the app has an install that returns True or False. For example: At the time of login, choose Login mode will determine whether it is installed, if not installed there is a dialog box, installed to jump to the login page,

driver.find_element_by_id ("Weixin_login_button"). Click () If driver.is_app_installed ("weixin.apk"):    //To do Input User, Passwdelse:    //Show Dialog

(3) Install_app

Install_app ()

After the last example, if the dialog box is not installed, check the dialog before installing the app. Special note: "weixin.apk" in the example refers to App_path + Package_name,

driver.find_element_by_id ("Weixin_login_button"). Click () If driver.is_app_installed ("weixin.apk"):    //To do Input User, Passwdelse:    check_dialog ()    Driver.install_app ("weixin.apk")

(4) Remove_app

Remove_app ()

When testing older versions of compatible use cases, replace the new version with the old version, you need to uninstall the new version, and then install the old version, so you need to call this method,

Driver.remove_app ("new_app.apk")  # Uninstall Driver.install_app ("old_app.apk") # Install

(5) Launch_app

Launch_app ()

Open a capabilities configured device app. This method is not currently used. Wait for later to do the update.

(6) Close_app

Close_app ()

Close the app app. This method is commonly used at the end of code, when objects are cleaned and disposed. Combined with UnitTest Framework Common teardown () used,

Import Unittestclass Demo (unittest. TestCase):    def setUp (self):        pass        def tearDown (self):        Driver.close_app ()        driver.quit ()

(7) Start_activity

start_activity ()

This method is intended for use with two or more apps in the test. For example, in a motion-related test, you first need to turn on the GPS simulation tool and start the dot. Then open the plump Select motion type to start the movement, then you can start the capabilities configuration to open the GPS tool, turn on the pace of the control and then open the plump app,

Driver = Webdriver. Remote (' Http://localhost:4723/wd/hub ', desired_caps={' platformname ': ' Android ',                        ' devicename ': ' Android Mechine ',                        ' apppackage ': ' Package of Gpstools ',                        ' Unicodekeyboard ': true,                        ' Resetkeyboard ': true,                        ' NoReset ': True,                        ' appactivity ': ' Activity of Gpstools '} ' # to do Gps Mock actiondriver.start_activity ("Com.codoon.gps", " Ui.login.welcomeActivity ")

(8) Wait_activity

wait_activity ()

This method is suitable for one of the Appium wait methods. Whether it is Webdriver or appium, the waiting method is divided into three types: explicit wait, implicit wait, time.sleep, from the wait_activity source code can be seen, is an implicit wait. The waiting method can be opened in a separate topic detailed description, here do not repeat.

This method mainly uses waiting when the network load is required, such as when the user logs on as a precondition, Wait_activity accepts three parameters: the name of the activity to wait for loading, timeout time-out (in seconds), detection interval (seconds),

Driver.login_action () driver.wait_activity ("Homepage.activity", 1) driver.find_element_by_id ("my"). Click ()

The implication is that the activity of the homepage waiting to load the app appears, waiting for a maximum time of 30 seconds, every 1 seconds to detect whether the current Activity equals homepage activity. If, then launch Wait, execute click on my tab action, if no, then continue to wait, 30 seconds after the prompt timeout throws an exception.

Iv. Other (in this category, the main addition to the above-mentioned API method)

(1) screenshot

Get_screenshot_as_file ()

Usage: Driver.get_screenshot_as_file ('.. /screenshot/foo.png '), accept the parameter as the saved picture path and name

(2) Size and location

size () Location ()

Size and location are the acquisition of element locations and dimensions, which are mainly used in the case of a removable control, such as a perfect profile page, where the birthday, height and weight need to be scratched. The swipe and flick we mentioned before are scratched against the screen of the device, which is obviously not applicable here. And there is no specific method, so we need to scrub the movable controls ourselves,

Swipe_control ()

(3) Get control various properties

View Code

Usage: driver.find_element_by_id (). Get_attribute (name), name is the flag on the left (class,package,checkable,checked ...), the return value is str type, True or false, but is actually "true" or "false"

(4) Pull_file

Pull_file ()

Pull the files on the device to the local hard disk, in the mobile phone number registration needs to obtain the mobile phone verification code, the implementation method is to use another apk extracted to the verification code exists in the phone memory, and then use Pull_file to obtain the verification code content, so that appium can be the correct verification code to fill in.


This section appium some of the commonly used API functions, which need to be supplemented slowly in the future. Although not exhaustive, the actual projects involved have been almost mentioned. When we test a function, we must first operate on it, this time we should consider to find the corresponding object element, call the specific event class function, verify the result, we want to detect the result of the operation is not consistent with our expectations? Then it is necessary to consider the corresponding Assert function (i.e. assertion). So remember these six words: Object-Event-assertion, which allows you to start writing corresponding automated test cases for any app.


Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.