界面操作和 adb 命令
掌握 APP 常用的界面交互操作
掌握常用 adb 命令与使用场景
能实现滑动、按键、手势等操作
核心讲解
(1)基础元素操作.click():点击.send_keys():输入文本.clear():清空输入框.text:获取元素文本.get_attribute():获取属性.is_displayed():是否可见
swipe(x1, y1, x2, y2, duration):从坐标 (x1,y1) 滑动到 (x2,y2)向上滑:x 不变,y 从大到小
向下滑:x 不变,y 从小到大
向左滑:y 不变,x 从大到小
scroll():滚动drag_and_drop():拖拽元素
driver.press_keycode(键码),模拟手机物理按键。 常用键码:
4:返回键
3:Home 键
24:音量 +
25:音量 -
66:回车
adb 是 Android 调试桥,电脑和手机通信的工具。
adb devices:查看连接的设备adb install xxx.apk:安装 APKadb uninstall 包名:卸载 APPadb shell:进入手机 shelladb shell screencap -p /sdcard/1.png:截图adb pull /sdcard/1.png:把手机文件拉到电脑adb push 1.png /sdcard/:把电脑文件推到手机adb logcat:查看日志
代码示例
from appium import webdriver
from appium.webdriver.common.appiumby import AppiumBy
import time
desired_caps = {
"platformName": "Android",
"deviceName": "127.0.0.1:62001",
"appPackage": "com.android.settings",
"appActivity": ".Settings",
"noReset": True
}
driver = webdriver.Remote("http://127.0.0.1:4723/wd/hub", desired_caps)
time.sleep(2)
# 获取屏幕尺寸
size = driver.get_window_size()
width = size["width"]
height = size["height"]
print(f"屏幕尺寸:{width}x{height}")
# 向上滑动页面(从下往上滑)
start_x = width / 2
start_y = height * 0.8
end_y = height * 0.2
driver.swipe(start_x, start_y, start_x, end_y, 1000)
time.sleep(1)
# 向下滑动
driver.swipe(start_x, end_y, start_x, start_y, 1000)
time.sleep(1)
# 点击搜索
driver.find_element(AppiumBy.ID, "com.android.settings:id/search").click()
time.sleep(1)
# 输入内容
input_box = driver.find_element(AppiumBy.CLASS_NAME, "android.widget.EditText")
input_box.send_keys("蓝牙")
time.sleep(1)
# 按返回键
driver.press_keycode(4)
time.sleep(1)
# 按Home键回到桌面
driver.press_keycode(3)
# ===== adb命令调用示例 =====
import os
# 查看设备
os.system("adb devices")
# 截图
os.system("adb shell screencap -p /sdcard/setting.png")
os.system("adb pull /sdcard/setting.png .")
driver.quit()
常见误区
滑动坐标写死:不同手机分辨率不一样,按比例计算坐标,不要写死像素
滑动太快找不到元素:duration 设长一点,滑动太快页面来不及加载
中文输入乱码:要设置 unicodeKeyboard 参数,支持中文输入
adb 命令找不到:配置 ANDROID_HOME 环境变量,platform-tools 加入 path
课后练习
实现:从下往上滑动设置页面,找到 “关于手机” 并点击进入
模拟按返回键两次,回到桌面
用 adb 命令安装一个 APK 到手机,再卸载
