文章目录
- 1. 启动新app
- 2. 关闭app
- 3. 安装apk到手机
- 4. 从手机卸载app
- 5. 判断app是否安装
- 6. base64加密、解码
- 7. 发送文件到手机
- 8. 从手机拉取文件
- 9. 获取当前屏幕元素结构
- 10. 查看手机页面元素
- 11. 截图问题
- 12. id定位元素
- 13. class定位元素
- 14 点击方法
- 15. xpth定位元素
- 16. 三种定位使用优先级
- 17. 练习1
- 18. 定位一组元素
- 19. 获取元素text文本属性值
- 20. 显示等待
- 21. 输入文本内容到手机
- 22 清空输入框
- 23 获取元素属性值
- 24. 获取元素屏幕坐标
- 25 获取元素大小--扩展
- 26. 获取app包名、启动名
- 27. 练习
1. 启动新app
driver.start_activity("包名","启动名")
# 短信包名 启动名 com.android.mms .ui.ConversationList
# 启动短信
driver.start_activity("com.android.mms", ".ui.ConversationList")
import time
from appium import webdriver
desired_caps = dict()
desired_caps["platformName"] = 'Android'
desired_caps["platformVersion"] = '5.1'
desired_caps["deviceName"] = 'sanxing'
desired_caps["appPackage"] = 'com.android.setting'
desired_caps["appActivity"] = '.Settings'
driver = webdriver.Remote("http://127.0.0.1:4723/wd/hub", desired_caps)
time.sleep(2)
driver.start_activity("com.android.mms",".ui.ConversationList")
2. 关闭app
driver.close_app() # 关闭app 但不会关闭驱动对象
driver.quit() # 关闭app 同时关闭驱动对象
"""close_app()"""
time.sleep(2)
driver.close_app()
time.sleep(2)
driver.start_activity("com.android.mms", ".ui.ConversationList")
"""quit()"""
time.sleep(2)
driver.quit()
driver.start_activity("com.android.mms", ".ui.ConversationList")
3. 安装apk到手机
driver.install_app("apk文件绝对路径")
# 兼容系统写法
driver.install_app(os.getcwd() + os.sep + "com.example.corel.calc_2.1.1023_11.apk")
4. 从手机卸载app
driver.remove_app("app包名") # 注意不能卸载系统app
import os
from appium import webdriver
desired_caps = dict()
desired_caps["platformName"] = 'Android'
desired_caps["platformVersion"] = '5.1'
desired_caps["deviceName"] = 'sanxing'
desired_caps["appPackage"] = 'com.android.settings'
desired_caps["appActivity"] = '.Settings'
driver = webdriver.Remote("http://127.0.0.1:4723/wd/hub", desired_caps)
driver.install_app(os.getcwd() + os.sep + 'com.example.corel.calc_2.1.1023_11.apk')
driver.remove_app("com.example.corel.calc")
driver.quit()
5. 判断app是否安装
driver.is_app_installed(app包名) # 如果手机安装返回True 未安装返回False
"""判断计算是否安装 安装->卸载 未安装->安装"""
isApp = driver.is_app_installed("com.example.corel.calc")
if isApp:
driver.remove_app("com.example.corel.calc")
else:
driver.install_app(os.getcwd() + os.sep + 'com.example.corel.calc_2.1.1023_11.apk')
6. base64加密、解码
import base64
value = "hello"
# base64加密
data = str(base64.b64encode(value.encode('utf-8')), 'utf-8')
print(data)
# base64解码
de_data = str(base64.b64decode(data), 'utf-8')
print("de_data:", de_data)
7. 发送文件到手机
driver.push_file("手机存储路径","base64编码数据")
import base64
str(base64.b64encode("数据".encode('utf-8')), 'utf-8')
"""
将hello写⼊到⼿机/sdcard/abc.txt
"""
data = str(base64.b64encode("hello".encode('utf-8')), 'utf-8')
driver.push_file("/sdcard/abc.txt", data)
❗注意:如果不指定手机文件存储名字,也可以完成发送,但是文件是以appium开头以.tmp结尾的临时文件,不方便维护
8. 从手机拉取文件
driver.pull_file("手机文件路径") # 返回⽂件中经过base64编码数据
import base64
str(base64.b64decode(编码数据), 'utf-8')
"""
将⼿机/sdcard/abc.txt⽂件数据拉取到电脑
"""
data = driver.pull_file('/sdcard/abc.txt')
print("拉取回数据:", data)
re_data = str(base64.b64decode(data), 'utf-8')
print("解码后数据:", re_data)
9. 获取当前屏幕元素结构
driver.page_source # 返回当前屏幕内元素的xml字符串
❗ 注意:每一个元素都包含一些属性和属性值
# 写入文件
with open("./page.xml", 'w') as f:
f.write(driver.page_source)
10. 查看手机页面元素
uiautomatorviewer
位置:sdk家目录下的tools目录中(从系统变量中找)
使用时:
1.手机需要打开对应页面,在使用uiautomatorviewer截图
2.找元素找可选中最⼩单位
元素属性:
text属性
resource-id属性
class属性
content-desc属性
11. 截图问题
当截图工具出现以下问题
解决办法:adb kill-server
12. id定位元素
driver.find_element_by_id("resource-id属性值")
13. class定位元素
driver.find_element_by_class_name("class属性值")
14 点击方法
定位对象.click()
import time
from appium import webdriver
desired_caps = dict()
desired_caps["platformName"] = "Android"
desired_caps["platformVersion"] = "5.1"
desired_caps["deviceName"] = "sanxing"
desired_caps["appPackage"] = "com.android.settings"
desired_caps["appActivity"] = ".Settings"
driver = webdriver.Remote("http://127.0.0.1:4723/wd/hub", desired_caps)
driver.find_element_by_id("com.android.settings:id/search").click()
time.sleep(1)
driver.find_element_by_class_name("android.widget.ImageButton").click()
time.sleep(1)
driver.quit()
15. xpth定位元素
driver.find_element_by_xpath(xpath语句)
xpath语句:
1."//*[contains(@text, 'text属性值')]"
2."//*[contains(@class, 'class属性值')]"
3."//*[contains(@resource-id, 'resource-id属性值')]"
import time
from appium import webdriver
desired_caps = dict()
desired_caps['platformName'] = 'Android'
desired_caps['platformVersion'] = '5.1'
desired_caps['deviceName'] = 'sanxing'
desired_caps['appPackage'] = 'com.android.settings'
desired_caps['appActivity'] = '.Settings'
driver = webdriver.Remote("http://127.0.0.1:4723/wd/hub", desired_caps)
search_btn = "//*[contains(@resource-id, 'com.android.settings:id/search')]"
driver.find_element_by_xpath(search_btn).click()
time.sleep(1)
search_return_btn = "//*[contains(@class, 'android.widget.ImageButton')]"
driver.find_element_by_xpath(search_return_btn).click()
time.sleep(1)
more_btn = "//*[contains(@text, '更多')]"
driver.find_element_by_xpath(more_btn).click()
time.sleep(1)
driver.quit()
16. 三种定位使用优先级
优先使用:
id class
其次使用:
xpath
能使用id, class定位元素不要使用xpath,最后定位不到使用xpath
17. 练习1
练习:发文件 拉取文件
1.电脑有⽂件hello.txt ⾥⾯包含:123 appium
2.将hello.txt⽂件内容发送到⼿机/sdcard/data.txt⽂件中
3.将⼿机/sdcard/data.txt数据拉取到电脑并存储到当前⽬录 app.txt
import base64, time
from appium import webdriver
desired_caps = dict()
desired_caps['platformName'] = 'Android'
desired_caps['platformVersion'] = '5.1'
desired_caps['deviceName'] = 'sanxing'
desired_caps['appPackage'] = 'com.android.settings'
desired_caps['appActivity'] = '.Settings'
driver = webdriver.Remote("http://127.0.0.1:4723/wd/hub", desired_caps)
"""
1.电脑有文件hello.txt 里面包含:123 appium
2.将hello.txt文件内容发送到手机/sdcard/data.txt文件中
3.将手机/sdcard/data.txt数据拉取到电脑并存储到当前目录 app.txt中
"""
with open("./hello.txt", "r") as f:
base_data = str(base64.b64encode(f.read().encode('utf-8')), 'utf-8')
driver.push_file("/sdcard/data.txt", base_data)
with open("./app.txt", "w") as f:
base_re_data = str(base64.b64decode(driver.pull_file("/sdcard/data.txt")), 'utf-8')
f.write(base_re_data)
driver.quit()
18. 定位一组元素
driver.find_elements_by_id("resource-id属性值")
driver.find_elements_by_class_name("class属性值")
driver.find_elements_by_xpath(xpath语句)
❗注意:
返回值为定位给对象的列表,如果需要使用列表中的值,需要遍历
import base64, time
from appium import webdriver
desired_caps = dict()
desired_caps['platformName'] = 'Android'
desired_caps['platformVersion'] = '5.1'
desired_caps['deviceName'] = 'sanxing'
desired_caps['appPackage'] = 'com.android.settings'
desired_caps['appActivity'] = '.Settings'
driver = webdriver.Remote("http://127.0.0.1:4723/wd/hub", desired_caps)
ids_value = driver.find_elements_by_id("com.android.settings:id/title")
for i in ids_value:
print("定位对象:", i)
print("文本:", i.text)
classes_value = driver.find_elements_by_class_name("android.widget.TextView")
for i in classes_value:
print("对象:", i)
print("文本:", i.text)
xpath_value = "//*[contains(@text, '示')]"
xpath_values = driver.find_elements_by_xpath(xpath_value)
for i in xpath_values:
print("对象:", i)
print("文本:", i.text)
driver.quit()
19. 获取元素text文本属性值
定位对象.text
import base64, time
from appium import webdriver
desired_caps = {}
desired_caps['platformName'] = 'Android'
desired_caps['platformVersion'] = '5.1'
desired_caps['deviceName'] = 'sanxing'
desired_caps['appPackage'] = 'com.android.settings'
desired_caps['appActivity'] = '.Settings'
driver = webdriver.Remote("http://127.0.0.1:4723/wd/hub", desired_caps)
values = driver.find_elements_by_id("com.android.settings:id/title")
for i in values:
if i.text == "更多":
i.click()
break
driver.quit()
20. 显示等待
超时时间范围内: 5
搜索间隔时间: 1
找到元素:返回定位对象
找不到元素:报超时异常
显示等待⽅法
1.导⼊类
from selenium.webdriver.support.wait import WebDriverWait
2.使用方式
WebDriverWait(driver, timeout, pull).until(method)
参数:
driver:⼿机驱动对象
timeout:搜索元素超时时间
poll:搜索间隔 默认0.5s
method:匿名函数
单个元素
lambda x: x.find_element_by_id("resource-id属性值")
lambda x: x.find_element_by_class_name("class属性值")
lambda x: x.find_element_by_xpath("xpath语句")
一组元素
lambda x: x.find_elements_by_id("resource-id属性值")
lambda x: x.find_elements_by_class_name("class属性值")
lambda x: x.find_elements_by_xpath("xpath语句")
超时异常演示
# 找不到元素报超时异常
WebDriverWait(driver, 5, 1).until(lambda x: x.find_element_id("com.android.settings:id/search123")).click()
异常类型:
selenium.common.exceptions.TimeoutException
"""验证查找元素时间"""
try:
# 开始时间
print("开始时间:", time.strftime("%H:%M:%S", time.localtime()))
WebDriverWait(driver, 5, 1).until(lambda x: x.find_element_by_id("com.android.settings:id/search123")).click()
except:
# 结束时间
print("结束时间:", time.strftime("%H:%M:%S", time.localtime()))
❗注意:
显示等待使用场景:
1.手机不确定是否卡顿
2.不确定手机网络,所有和网络相关的操作
import base64, time
from appium import webdriver
from selenium.webdriver.support.wait import WebDriverWait
desired_caps = dict()
desired_caps["platformName"] = "Android"
desired_caps["platformVersion"] = "5.1"
desired_caps["deviceName"] = "sanxing"
desired_caps["appPackage"] = "com.android.settings"
desired_caps["appActivity"] = "Settings"
driver = webdriver.Remote("http://127.0.0.1:4723/wd/hub", desired_caps)
"""验证查找元素时间"""
try:
print("开始时间:", time.strftime("%H:%M:%S", time.localtime()))
WebDriverWait(driver, 5, 1).until(lambda x: x.find_element_by_id("com.android.settings:id/search123")).click()
except:
print("# 结束时间:", time.strftime("%H:%M:%S", time.localtime()))
time.sleep(2)
driver.quit()
21. 输入文本内容到手机
定位对象.send_keys("输入文本内容")
❗注意:
输入中文时,需要添加启动参数支持
desired_caps["resetKeyboard"] = True # 重置键盘
desired_caps["unicodeKeyboard"] = True # 使⽤unicode键盘
import base64, time
from appium import webdriver
from selenium.webdriver.support.wait import WebDriverWait
desired_caps = {}
desired_caps['platformName'] = 'Android'
desired_caps['platformVersion'] = '5.1'
desired_caps['deviceName'] = 'sanxing'
desired_caps['appPackage'] = 'com.android.settings'
desired_caps['appActivity'] = '.Settings'
desired_caps['resetKeyboard'] = True
desired_caps['unicodeKeyboard'] = True
driver = webdriver.Remote("http://127.0.0.1:4723/wd/hub", desired_caps)
driver.find_element_by_id("com.android.settings:id/search").click()
search_input = driver.find_element_by_id("android:id/search_src_text")
search_input.send_keys("$%123hello")
search_inputc.clear()
search_input.send_keys("中国")
time.sleep(2)
driver.quit()
22 清空输入框
定位对象.clear()
❗注意:
在同⼀个输⼊框进⾏连续输⼊时,每次输⼊前需要进⾏清空操作
1.防⽌有默认值
2.多次输⼊数据不影响
23 获取元素属性值
定位对象.get_attribute(value)
参数:
value="name" 获取元素content-desc属性值,也可以获取text属性值
value="text" 获取元素text属性值
value="className" 获取元素class属性值
value="resourceId" 获取元素resource-id属性值
例⼦:
# 搜索按钮 "com.android.settings:id/search"
search =
driver.find_element_by_id("com.android.settings:id/search")
# 取resource-id
print("resource-id:", search.get_attribute("resourceId"))
# 取class
print("class:", search.get_attribute("className"))
# 取content-desc
print("content-desc:", search.get_attribute("name"))
# 定位⽆线和⽹络
wlan_net =
driver.find_element_by_id("com.android.settings:id/category_title")
# 取text
print("text:",wlan_net.get_attribute("text"))
import base64, time
from appium import webdriver
from selenium.webdriver.support.wait import WebDriverWait
desired_caps = {}
desired_caps['platformName'] = 'Android'
desired_caps['platformVersion'] = '5.1'
desired_caps['deviceName'] = 'sanxing'
desired_caps['appPackage'] = 'com.android.settings'
desired_caps['appActivity'] = '.Settings'
desired_caps['resetKeyboard'] = True
desired_caps['unicodeKeyboard'] = True
driver = webdriver.Remote("http://127.0.0.1:4723/wd/hub", desired_caps)
search = driver.find_element_by_id("com.android.settings:id/search")
print("resource-id:", search.get_attribute("resourceId"))
print("class:", search.get_attribute("className"))
print("content-desc:", search.get_attribute("name"))
wlan_net = driver.find_element_by_id("com.android.settings:id/category_title")
print("text:", wlan_net.get_attribute("text"))
time.sleep(2)
driver.quit()
24. 获取元素屏幕坐标
定位对象.location # 返回值字典 {"x":x,"y":y}
❗注意:
坐标点为元素在屏幕上左上⻆的坐标
⼿机:
坐标系
左上⻆: (0,0)
右下⻆:(屏幕最⼤分辨率)
25 获取元素大小–扩展
定位对象.size # 返回字典 {"height":h,"width":w}
import base64, time
from appium import webdriver
from selenium.webdriver.support.wait import WebDriverWait
desired_caps = {}
desired_caps['platformName'] = 'Android'
desired_caps['platformVersion'] = '5.1'
desired_caps['deviceName'] = 'sanxing'
desired_caps['appPackage'] = 'com.android.settings'
desired_caps['appActivity'] = '.Settings'
desired_caps['resetKeyboard'] = True
desired_caps['unicodeKeyboard'] = True
driver = webdriver.Remote("http://127.0.0.1:4723/wd/hub", desired_caps)
more = driver.find_element_by_xpath("//*[contains(@text,'更多')]")
print("类型:", type(more.location))
print("更多按钮:", more.location)
print("更多大小:", more.size)
time.sleep(2)
driver.quit()
26. 获取app包名、启动名
# 获取app包名
print("包名:", driver.current_package)
# 获取app启动名
print("启动名:", driver.current_activity)
import base64, time
from appium import webdriver
from selenium.webdriver.support.wait import WebDriverWait
desired_caps = {}
desired_caps['platformName'] = 'Android'
desired_caps['platformVersion'] = '5.1'
desired_caps['deviceName'] = 'sanxing'
desired_caps['appPackage'] = 'com.android.settings'
desired_caps['appActivity'] = '.Settings'
desired_caps['resetKeyboard'] = True
desired_caps['unicodeKeyboard'] = True
driver = webdriver.Remote("http://127.0.0.1:4723/wd/hub", desired_caps)
print("包名:", driver.current_package)
print("启动名:", driver.current_activity)
time.sleep(2)
driver.quit()
27. 练习
搜索三个内容,并判断搜索成功
搜索内容:
输⼊:1,判断“休眠”
输⼊:m,判断“MAC地址”
输⼊:w,判断“WPS按钮”
import base64, time
from appium import webdriver
from selenium.webdriver.support.wait import WebDriverWait
desired_caps = {}
desired_caps['platformName'] = 'Android'
desired_caps['platformVersion'] = '5.1'
desired_caps['deviceName'] = 'sanxing'
desired_caps['appPackage'] = 'com.android.settings'
desired_caps['appActivity'] = '.Settings'
desired_caps['resetKeyboard'] = True
desired_caps['unicodeKeyboard'] = True
driver = webdriver.Remote("http://127.0.0.1:4723/wd/hub", desired_caps)
"""
搜索三个内容,并判断搜索成功
搜索内容:
输入:1,判断“休眠”
输入:m,判断“MAC地址”
输入:w,判断“WPS按钮”
"""
driver.find_element_by_id("com.android.settings:id/search").click()
search_text = [{"key": "1", "res": "休眠"}, {"key": "m", "res": "MAC地址"}, {"key": "w", "res": "WPS按钮"}]
for i in search_text:
search_input = driver.find_element_by_id("android:id/search_src_text")
search_input.clear()
search_input.send_keys(i.get("key"))
results = driver.find_elements_by_id("com.android.settings:id/title")
values = []
for o in results:
values.append(o.text)
if i.get("res") in values:
print("搜索成功")
else:
print("搜索失败")
time.sleep(2)
driver.quit()