app自动化测试---webview 元素定位选取(app中H5页面元素定位)

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版本下载对应的驱动。

     下载地址: https://npm.taobao.org/mirrors/chromedriver/

 

 

 

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()

 

posted @ 2021-06-23 10:52  Z_sun  阅读(1130)  评论(0编辑  收藏  举报