在混合開發的App中,常常會有內嵌的H5頁面。那麼這些H5頁面元素該如何進行定位操做呢?html
針對這種場景直接使用前面所講的方法來進行定位是行不通的,由於前面的都是基於Andriod原生控件進行元素定位,而Web網頁是單獨的B/S架構,二者的運行環境不一樣所以須要進行上下文(context)切換,而後對H5頁面元素進行定位操做。node
關於應用程序環境的全局信息的接口。 這是一個抽象類,其實現由Android系統提供。 它容許訪問特定於應用程序的資源和類,以及對應用程序級操做的調用,如啓動活動、廣播和接收意圖等。android
在程序中context咱們能夠理解爲當前對象在程序中所處的一個環境。 好比前面提到的App一個界面是屬於Activity類型,也就是Android界面環境,可是當訪問內嵌的網頁是屬於另一個環境(網頁環境),二者處於不一樣的一個環境。web
例子地址:https://drfone.wondershare.com/backup.htmlchrome
WebView是Android系統提供能顯示網頁的系統控件,它是一個特殊的View,同時它也是一個ViewGroup,能夠有不少其餘子View。npm
NATIVE_APP:這個就是native,也就是原生的瀏覽器
driver.switch_to.context("NATIVE_APP")網絡
WEBVIEW_com.xxxx :這個就是webview架構
driver.switch_to.context("WEBVIEW_com.xxxx")app
1.PC版谷歌瀏覽器下載,官網地址下載
2.手機版Chrome瀏覽器 推薦用Google play去下載
3.Chrome driver 下載 須要根據本身電腦上下載的谷歌版本相匹配,ChromeDriver版本與Chrome版本對應表
下載後放置此路徑下C:\Users\XXX\AppData\Local\appium-desktop\app-1.5.0\resources\app\node_modules\appium\node_modules\appium-chromedriver\chromedriver\win
if (Build.VERSION.SDK_INT >=Build.VERSION_CODES.KITKAT) {
WebView.setWebContentsDebuggingEnabled(true);
注:此步驟,通常須要App開發人員開啓。
場景:啓動dr.fone app 進入backup H5頁面中的輸入郵箱並點擊提交,而後返回
測試設備:逍遙模擬器 Android 5.1 /Chrome 78.0.3904.96
PC系統環境: Win7 64bit /79.0.3945.79(最好跟手機端的版本保持一致吧)
測試app: dr.fone3.2.0.apk
H5頁面地址:https://drfone.wondershare.com/backup.html
獲取方法實踐
contexts=driver.contexts
print(contexts)
#打印結果
具體代碼:
# -*- coding: utf-8 -*-#
from appium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
from selenium.common.exceptions import NoSuchElementException
import time
desired_caps = {
"platformName": "Android",
"platformVersion": "5.1",
"deviceName": "U4KF9HSK99999999",
"appPackage": "com.wondershare.drfone",
"appActivity": "com.wondershare.drfone.ui.activity.WelcomeActivity",
"unicodeKeyboard":True,
"resetKeyboard":True,
"noReset": True,
#"ANDROID_UIAUTOMATOR":"Uiautomator2",
# "chromeOptions": {"androidProcess": "com.wondershare.drfone"}
}
driver = webdriver.Remote("http://localhost:4723/wd/hub",desired_caps)
driver.implicitly_wait(5)
print("click backipbtn")
driver.find_element_by_id("com.wondershare.drfone:id/btnBackup").click()
element= WebDriverWait(driver,30).until(lambda x:x.find_element_by_id("com.wondershare.drfone:id/btnRecoverData"))
print("click nextbtn")
element.click()
try:
time.sleep(2)
driver.find_element_by_class_name("android.webkit.WebView")
except NoSuchElementException:
#防止網絡中斷,刷新一下
print("no network")
driver.find_element_by_id("com.wondershare.drfone:id/online_error_btn_retry").click()
contexts=driver.contexts
print(contexts)
else:
contexts=driver.contexts
print(contexts)
print("switch to webview")
time.sleep(2)
driver.switch_to.context('WEBVIEW_com.wondershare.drfone')
print("編輯郵箱,提交")
driver.find_element_by_id("email").send_keys("123456@qq.com")
driver.find_element_by_class_name("btn_send").click()
print("switch to native")
driver.switch_to.context(contexts[0])
driver.find_element_by_class_name("android.widget.ImageButton").click()
參考轉載:https://www.cnblogs.com/xuzhongtao/p/9723210.html