1.說明
混合app中會使用到原生組件以及webview 視圖。webview 中嵌套網頁。此時,我們用之前的元素定位方式就會定位不到
cmd命令中啟動appium,再打開C:\Users\hy\AppData\Local\Android\Sdk\tools\bin 下面的 uiautomatorviewer.bat
2.准備環境
Edge 瀏覽器 或 Chrome瀏覽器(需要FQ)
1. 在瀏覽器的地址欄中輸入 edge://inspect/#devices 或者 chrome://inspect/#devices
2. 在模擬器的 瀏覽器中打開網址
3. 點擊 inspect 進行WebView 元素定位
4. 下載chromeDriver
注意:如果調試的時候,我們在瀏覽器中無法獲取webview 頁面信息(app中如果需要 調試 webview 頁面),則需要開發在測試版本中的app 進行配
配置參考文檔: https://developer.chrome.com/docs/devtools/remote-debugging/webviews/
# 需要在 app 中添加配置 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) { WebView.setWebContentsDebuggingEnabled(true); }
(4)下載chromedriver
根據在瀏覽器中看到 手機端使用的Chrome版本下載對應的驅動。
3. 代碼
import selenium.webdriver.support.expected_conditions as EC from selenium.webdriver.common.by import By from appium import webdriver import time import os from selenium.webdriver.support.wait import WebDriverWait chromedriver= os.path.join(os.path.dirname(os.path.abspath(__file__)),'driver/chrome/75.0.3770.140/chromedriver.exe') desired_caps = { 'platformName':'Android', # 測試Android系統 'platformVersion':'7.1.2', # Android版本 可以在已連接手機 設置->關於手機 中查看 'deviceName':'127.0.0.1:62001', # cmd中使用 adb devices 命令查看已連接的設備 'automationName':'UiAutomator2', # 自動化引擎(默認UiAutomator2即可) 'noReset': True, # 不要重置app的狀態(比如,已經登陸的app,我們運行項目的時候保留之前的狀態) 'fullReset': False, # 不要清理app的緩存數據(比如,已經登陸的app,我們運行項目的時候保留之前的狀態) 'chromedriverExecutable': chromedriver, # chromedriver 對應的絕對路徑 'appPackage':"org.cnodejs.android.md", # 應用的包名(打開對應包名的app) 'appActivity': ".ui.activity.MainActivity" # 應用的活動頁名稱 } driver = webdriver.Remote('http://127.0.0.1:4723/wd/hub',desired_capabilities=desired_caps) time.sleep(6) # 如果根據這個id可以找到多個元素,會默認匹配第一個元素 driver.find_element_by_id('org.cnodejs.android.md:id/tv_title').click() # 等待webview 加載出來,等待5s wait = WebDriverWait(driver, 5) wait.until(EC.presence_of_element_located((By.CLASS_NAME, 'android.webkit.WebView'))) # 切換視圖 # 獲取所有的視圖 contexts = driver.contexts print(contexts) # ['NATIVE_APP', 'WEBVIEW_org.cnodejs.android.md'] # 切換到瀏覽器視圖中 driver.switch_to.context(contexts[-1]) # 可以使用瀏覽器的元素定位(點擊,關注) driver.find_element_by_xpath('//td[@class="right"]/img').click() # 再次從webview中切換回原生控件中 driver.switch_to.context(contexts[0]) driver.find_element_by_android_uiautomator('new UiSelector().className("android.widget.Button").text("登錄")').click()