Setting Up Python uiautomator2 for Android Automation
This tutorial explains how to set up Python 3.7, install ADB and UIAutomatorViewer, configure the uiautomator2 library and atx‑agent, and write a Python script that connects to an Android device to launch and interact with the Douyin app using various UI selectors.
Tool Preparation
Required tools: Python 3.7.7, adb (Android Debug Bridge), and uiautomatorviewer.
Install ADB
Download ADB from the official Android developer site, unzip, and add it to the system PATH.
Install UIAutomatorViewer
Connect the Android phone via USB, enable developer options and USB debugging.
Run adb devices -l on the computer to verify the connection.
Open UIAutomatorViewer and connect to the device.
Python Installation of uiautomator2
<code>pip install --pre -U uiautomator2</code>Install the atx‑agent on the device:
<code>python -m uiautomator2 init</code>Make sure to allow the installation of the uiautomator.apk on the device.
Write the Main Program
Example script to locate and interact with the Douyin app:
<code>import uiautomator2 as d
import time
def douyin():
# Connect via USB (replace with your device ID)
a = d.connect_usb('3d51a18c')
# Open Douyin
a(text="抖音极速版").click()
while True:
time.sleep(10)
# Swipe to next video
a.swipe(313, 1370, 313, 110)
if __name__ == '__main__':
douyin()
</code>Run the script; it will launch Douyin, then continuously swipe videos.
Original source: CSDN article
Python Programming Learning Circle
A global community of Chinese Python developers offering technical articles, columns, original video tutorials, and problem sets. Topics include web full‑stack development, web scraping, data analysis, natural language processing, image processing, machine learning, automated testing, DevOps automation, and big data.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.