Skip to content

Python Example 1 ​

Goal to Achieve ​

Open the Battery screen on an Android Smartphone using Python.

Battery Settings

Steps to reproduce: ​

  • Unlock the Device using PIN.
  • Open Settings.
  • Scroll to "Battery" option and click on it.

Prerequisites ​

Project Setup ​

  1. Create a project folder named android-python-1 with two files, as follows:

    └── android-python-1/
       ├── test_battery.py
       └── requirements.txt
  2. Copy the following content to the requirements.txt file:

    txt
    Appium-Python-Client
  3. Copy the following content to the test_battery.py file:

    python
    import unittest
    from appium.webdriver.webdriver import WebDriver
    from appium.options.android.uiautomator2.base import UiAutomator2Options
    from appium.webdriver.common.appiumby import AppiumBy
    
    capabilities = dict(
        platformName='Android',
        automationName='uiautomator2',
        udid='000000000', # <-- Change this to your device's ID
        autoGrantPermissions=True,
        autoUnlock=True,
        unlockType='pin',
        unlockKey='123456', # <-- Change this to your device's PIN
        appPackage='com.android.settings',
        appActivity='.Settings',
    )
    
    appium_server_url = 'http://localhost:4723'
    
    class TestAppium(unittest.TestCase):
        def setUp(self) -> None:
            self.driver = WebDriver(appium_server_url, options=UiAutomator2Options().load_capabilities(capabilities))
    
        def tearDown(self) -> None:
            if self.driver:
                self.driver.quit()
    
        def test_find_battery(self) -> None:
            battery_menu = 'Bateria' # <-- Change this to your Battery menu text if needed
            el = self.driver.find_element(
                by=AppiumBy.ANDROID_UIAUTOMATOR,
                value=f'new UiScrollable(new UiSelector().scrollable(true)).scrollIntoView(new UiSelector().text("{battery_menu}"));')
            el.click()
    
    if __name__ == '__main__':
        unittest.main()
  4. Initialize the Python virtual environment. Follow the instructions here.

  5. Install the dependencies:

    shell
    pip install -r requirements.txt

Capabilities ​

Before running, you need to adjust the capabilities dictionary:

  • udid:
    Replace '000000000' with the ID of your connected device.
    You can find this ID as explained here.
  • unlockKey:
    Replace '123456' with the PIN of the device you are using for the test.

Running the script ​

To run the script, execute the following command in your terminal (with the virtual environment activated):

shell
python test_battery.py