下面是一個完整的 Appium WebDriver 支持的常用方法匯總,并附上典型用法示例。
?一、元素查找方法/元素操作方法
? 使用?find_element()
?和?find_elements()
from appium import webdriver
from appium.webdriver.common.appiumby import AppiumBy# 單個元素查找
el = driver.find_element(by=AppiumBy.ID, value="com.example:id/username")# 多個元素查找
els = driver.find_elements(by=AppiumBy.CLASS_NAME, value="android.widget.EditText")
? 支持的定位方式(AppiumBy
):
定位方式 | 示例值 |
---|---|
AppiumBy.ID | "com.example:id/btn_login" |
AppiumBy.CLASS_NAME | "android.widget.EditText" |
AppiumBy.NAME | "login_button" (已不推薦) |
AppiumBy.XPATH | "//android.widget.TextView[@text='Submit']" |
AppiumBy.ACCESSIBILITY_ID | "button_login" |
AppiumBy.ANDROID_UIAUTOMATOR | 'new UiSelector().resourceId("com.example:id/login")' |
AppiumBy.IOS_PREDICATE | "label == 'Login'" (iOS 專用) |
AppiumBy.IOS_CLASS_CHAIN | "XCUIElementTypeButton[1]" (iOS 專用) |
舉例說明常用的 Appium 定位方式(配合 Appium Inspector 使用)
我們以一個假設的登錄頁面為例,其中包含以下 UI 元素信息(通過 Appium Inspector 查看):
屬性 | 值 |
---|---|
用戶名輸入框 | resource-id="com.example:id/username" |
密碼輸入框 | class="android.widget.EditText" |
登錄按鈕 | text="Login" ?或?content-desc="login_button" |
發送按鈕 | resource-id="com.example:id/send" |
提交按鈕 | xpath="//android.widget.Button[@text='Submit']" |
? 示例 1:通過?ID
?定位(推薦)
from appium.webdriver.common.appiumby import AppiumBy# 定位發送按鈕
send_button = driver.find_element(by=AppiumBy.ID, value="com.example:id/send")
send_button.click()
? 示例 2:通過?XPath
?定位(靈活但效率略低)
submit_button = driver.find_element(by=AppiumBy.XPATH,value="//android.widget.Button[@text='Submit']"
)
submit_button.click()
? 示例 3:通過?Class Name
?定位(適用于多個同類型元素)
edit_text_list = driver.find_elements(by=AppiumBy.CLASS_NAME,value="android.widget.EditText"
)# 輸入用戶名到第一個 EditText
edit_text_list[0].send_keys("testuser")
? 示例 4:通過?Accessibility ID
(content-desc)定位
login_button = driver.find_element(by=AppiumBy.ACCESSIBILITY_ID,value="login_button"
)
login_button.click()
? 示例 5:通過?Text
?定位(注意大小寫和空格)
login_button = driver.find_element(by=AppiumBy.ANDROID_UIAUTOMATOR,value='new UiSelector().text("Login")'
)
login_button.click()
? 示例 6:模糊匹配文本(contains)
button = driver.find_element(by=AppiumBy.ANDROID_UIAUTOMATOR,value='new UiSelector().textContains("Sub")'
)
button.click()
? 示例 7:通過?resource-id
?+?text
?組合定位(更穩定)
element = driver.find_element(by=AppiumBy.ANDROID_UIAUTOMATOR,value='new UiSelector().resourceId("com.example:id/send").text("Send Message")'
)
element.click()
?? 使用new UiSelector()語法定位元素
在 Appium 自動化測試中,特別是在 Android 平臺上,new UiSelector()
是一種非常強大且靈活的定位元素方式。它屬于 Android UI Automator 提供的 API,允許你通過多種屬性組合來精確定位頁面上的控件。
1.什么是?new UiSelector()
UiSelector
?是 Android UI Automator 提供的一個類。- 在 Appium 中可以通過?
AppiumBy.ANDROID_UIAUTOMATOR
?來使用它。 - 它可以結合多個屬性(如?
text
,?resourceId
,?className
,?index
,?description
?等)進行查找,適合處理復雜的 UI 結構。
2.基本語法結構
from appium.webdriver.common.appiumby import AppiumByelement = driver.find_element(by=AppiumBy.ANDROID_UIAUTOMATOR,value='new UiSelector().<method>(<value>)'
)
?? 注意:傳入的是一個字符串表達式,語法要嚴格符合 Java 的寫法。
3.常用方法詳解與示例
? 1.?text(String text)
根據文本內容定位控件。
driver.find_element(by=AppiumBy.ANDROID_UIAUTOMATOR,value='new UiSelector().text("Login")'
)
適用于按鈕、TextView 等顯示文字的控件。
? 2.?textContains(String substr)
模糊匹配文本內容(包含子串)
driver.find_element(by=AppiumBy.ANDROID_UIAUTOMATOR,value='new UiSelector().textContains("Log")'
)
? 3.?textStartsWith(String prefix)
以某個前綴開頭的文本
driver.find_element(by=AppiumBy.ANDROID_UIAUTOMATOR,value='new UiSelector().textStartsWith("Wel")'
)
? 4.?textMatches(Pattern regex)
正則匹配文本內容
driver.find_element(by=AppiumBy.ANDROID_UIAUTOMATOR,value='new UiSelector().textMatches("^User\\d+$")' # 匹配 "User123"
)
? 5.?resourceId(String id)
通過資源 ID 定位控件(推薦用 AppiumBy.ID
更簡潔)
driver.find_element(by=AppiumBy.ANDROID_UIAUTOMATOR,value='new UiSelector().resourceId("com.example:id/username")'
)
? 6.?className(String className)
通過類名定位控件(如 EditText
, Button
)
driver.find_element(by=AppiumBy.ANDROID_UIAUTOMATOR,value='new UiSelector().className("android.widget.Button")'
)
? 7.?description(String contentDescription)
通過 content-desc
屬性定位(Accessibility ID)
driver.find_element(by=AppiumBy.ANDROID_UIAUTOMATOR,value='new UiSelector().description("menu_icon")'
)
? 8.?index(int index)
通過索引定位(慎用,容易變化)
# 找第一個 TextView
driver.find_element(by=AppiumBy.ANDROID_UIAUTOMATOR,value='new UiSelector().className("android.widget.TextView").index(0)'
)
? 9.?instance(int instance)
獲取某一類控件中的第幾個實例(類似 XPath 中的 [n])
# 獲取第二個 EditText
driver.find_element(by=AppiumBy.ANDROID_UIAUTOMATOR,value='new UiSelector().className("android.widget.EditText").instance(1)'
)
? 10. 組合使用多個條件
你可以組合多個條件來更精確地定位元素:
# 同時匹配 resourceId 和 text
driver.find_element(by=AppiumBy.ANDROID_UIAUTOMATOR,value='new UiSelector().resourceId("com.example:id/login").text("Login")'
)
? 11.注意事項
項目 | 說明 |
---|---|
性能 | 比?ID ?和?XPath ?略慢,但比 XPath 更穩定 |
推薦用途 | 復雜控件、動態內容、沒有唯一 ID 的場景 |
調試建議 | 使用 Appium Inspector 查看控件屬性 |
只能在 Android 上使用 | 不支持 iOS,iOS 需要用?IosUIAutomation ?或?Predicate String |
? 12.常見問題解答
? Q1:為什么找不到元素?
- 控件還沒加載出來,加?
time.sleep()
?或顯式等待; - 文本大小寫不一致,注意區分;
- 控件是動態生成的,嘗試換用其他屬性;
- 使用?
driver.page_source
?查看當前頁面結構。
? 13.常用定位方式對比
定位方式 | 示例值 | 特點 |
---|---|---|
AppiumBy.ID | "com.example:id/send" | 推薦使用,速度快,唯一性強 |
AppiumBy.XPATH | "//android.widget.Button[@text='Submit']" | 靈活但慢,適合結構化定位 |
AppiumBy.CLASS_NAME | "android.widget.EditText" | 多個元素時需結合索引 |
AppiumBy.ACCESSIBILITY_ID | "login_button" | 依賴無障礙描述,iOS 和 Android 都支持 |
AppiumBy.ANDROID_UIAUTOMATOR | 'new UiSelector().text("Login")' | Android 專屬,強大但語法復雜 |
? element支持的方法
在使用 Appium 定位到元素之后,除了 click()
動作之外,還有許多其他動作可以對這些元素執行。以下是幾種常見的操作方法:
1. 輸入文本
send_keys()
:向輸入框中輸入文本。element = driver.find_element(by=AppiumBy.ID, value="com.example:id/username") element.send_keys("testuser")
2. 清除文本
clear()
:清除輸入框中的現有文本。element = driver.find_element(by=AppiumBy.ID, value="com.example:id/username") element.clear()
3. 獲取文本
text
?屬性:獲取元素顯示的文本內容。element = driver.find_element(by=AppiumBy.ID, value="com.example:id/message") print(element.text)
4. 檢查元素是否可見或啟用
is_displayed()
:判斷元素是否對用戶可見。is_enabled()
:檢查元素是否可用(例如按鈕是否可點擊)。element = driver.find_element(by=AppiumBy.ID, value="com.example:id/loginButton") if element.is_displayed() and element.is_enabled():element.click()
5. 獲取屬性值
get_attribute(name)
:獲取元素的特定屬性值。element = driver.find_element(by=AppiumBy.ID, value="com.example:id/username") attribute_value = element.get_attribute("name") # 或者 "content-desc", "resource-id" 等
6. 提交表單
submit()
:對于某些支持提交的元素(如表單),可以調用此方法來提交。form_element = driver.find_element(by=AppiumBy.ID, value="com.example:id/loginForm") form_element.submit()
7. 觸摸手勢
雖然不是直接作用于元素的方法,但你可以通過 TouchAction
類對特定元素執行觸摸手勢:
- 長按、輕掃等。
from appium.webdriver.common.touch_action import TouchActionaction = TouchAction(driver) action.long_press(el=element).wait(1000).release().perform()
8. 元素等待
有時候你可能需要等待某個元素變為可見或者存在:
- 顯式等待:
from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as ECwait = WebDriverWait(driver, 10) element = wait.until(EC.visibility_of_element_located((AppiumBy.ID, "com.example:id/username")))
9. 獲取元素大小和位置
size
?屬性?和?location
?屬性:分別用于獲取元素的尺寸和屏幕上的位置。element = driver.find_element(by=AppiumBy.ID, value="com.example:id/username") print("Size:", element.size) print("Location:", element.location)
10. 截圖
盡管不是直接針對元素的方法,但你可以截取整個屏幕的截圖,然后根據需要裁剪出特定元素的部分:
driver.save_screenshot('screenshot.png')
:保存當前屏幕截圖。
📱 二、移動端專屬方法(來自?MobileCommand
)
這些方法只能在 Appium 中使用,Selenium 不支持。
? 1. 滑動屏幕(Swipe)
driver.swipe(start_x=100, start_y=800, end_x=100, end_y=200, duration=800)
? 2. 拖拽(Drag and Drop)
driver.drag_and_drop(origin_el, destination_el)
? 3. 按下和釋放(Touch Action)
from appium.webdriver.common.touch_action import TouchActionaction = TouchAction(driver)
action.press(x=100, y=500).wait(1000).release().perform()
更推薦使用新版的
W3CActions
方式。
? 4. 啟動應用 / 關閉應用
driver.activate_app('com.example.app') # 啟動應用
driver.background_app(5) # 將應用置于后臺運行5秒
driver.terminate_app('com.example.app') # 強制停止應用
? 5. 獲取當前應用信息
print("Current Package:", driver.current_package)
print("Current Activity:", driver.current_activity)
? 6. 安裝 / 卸載應用
driver.install_app('/path/to/app.apk')
driver.remove_app('com.example.app')
? 7. 判斷是否已安裝應用
if driver.is_app_installed('com.example.app'):print("App is installed.")
? 8. 切換上下文(WebView / Native)
contexts = driver.contexts
print("Available contexts:", contexts)driver.switch_to.context(contexts[-1]) # 切換到 WebView
? 9. 獲取系統時間
print("Device time:", driver.device_time)
? 10. 發送鍵事件(如返回、菜單)
driver.press_keycode(4) # 返回鍵 KEYCODE_BACK
? 11. 截圖
driver.save_screenshot('screen.png')
三、瀏覽器相關方法(Hybrid App 或 Webview)
如果你是在 WebView 中進行操作,可以使用類似 Selenium 的方式:
driver.get("https://example.com")
print("Current URL:", driver.current_url)
driver.back()
driver.forward()
四、鍵盤與輸入操作
el.send_keys("Hello World")
el.clear()
如果遇到中文輸入問題,可設置以下 Desired Capabilities:
'dict': {'resetKeyboard': True,'unicodeKeyboard': True
}
五、截圖與文件操作
driver.save_screenshot('test.png') # 保存截圖
driver.get_screenshot_as_base64() # 獲取 base64 編碼圖片
六、網絡與設備狀態
driver.is_locked() # 是否鎖屏
driver.unlock() # 解鎖
driver.lock(5) # 鎖屏5秒后自動解鎖
driver.set_network_connection(6) # 設置網絡連接類型
七、執行腳本(JavaScript、Driver Command)
result = driver.execute_script("mobile: scroll", {"direction": "down"})
你也可以直接調用底層命令:
driver.execute("mobile: longClickGesture", {"x": 100,"y": 100,"duration": 1000
})
八、會話控制
driver.quit() # 結束當前會話
driver.close_app() # 關閉當前應用但不結束會話
九、獲取日志(Logcat 等)
logs = driver.get_log('logcat')
for log in logs:print(log)
支持的日志類型包括:
logcat
bugreport
server
driver
client
十、完整方法列表(部分)
你可以通過以下方式查看所有可用的方法:
dir(driver)
或者訪問官方文檔:
🔗 Appium-Python-Client 文檔
? 總結:常用方法速查表
功能 | 方法 |
---|---|
查找元素 | find_element ,?find_elements |
觸摸操作 | swipe ,?drag_and_drop ,?press_keycode |
應用控制 | activate_app ,?terminate_app ,?background_app |
安裝卸載 | install_app ,?remove_app ,?is_app_installed |
上下文切換 | switch_to.context() |
輸入文本 | send_keys ,?clear |
截圖 | save_screenshot ,?get_screenshot_as_base64 |
執行腳本 | execute_script ,?execute |
日志獲取 | get_log('logcat') |
鎖屏操作 | is_locked ,?unlock ,?lock |
如果你有具體需求或想了解某個功能的詳細用法,歡迎告訴我,我可以為你提供代碼示例!