APP自动化--webview上下文翻动

发布时间 2023-06-02 18:54:00作者: 琉璃星眸
前提工作都做好,包括
1、开启webview,

打开app对应的h5页面,在 chrome://inspect/#devices 地址中,检查是否显示对应的webview,如没有,则当前未开启调试模式
开启方式:
在WebView类中调用静态方法setWebContentsDebuggingEnabled,这种需要App开发人员操作。
if (Build.VERSION.SDK_INT >=Build.VERSION_CODES.KITKAT) {
WebView.setWebContentsDebuggingEnabled(true);
————————————————

同时开发者模式打开多线程webview

2、拿到网页页面地址和手机浏览器版本信息

  • 手机与电脑连接,开启USB调试模式,通过adb devices可查看到此设备

  • 在手机端(模拟器)打开应用,进入H5页面

  •  

 3、在电脑端Chrome浏览器地址栏输入chrome://inspect/#devices,进入调试模式

 

4、下载对应Chromedriver

 

启动appium server
写下如下代码:
 1 #!/usr/bin/env python
 2 # -*- coding: utf-8 -*-
 3 # @Time    : 2023/6/2 16:52
 4 # @Author  : 
 5 # @File    : webview上下文翻动.py
 6 # @Software: PyCharm
 7 import json
 8 from appium.webdriver import Remote
 9 
10 url = "127.0.0.1:4723/wd/hub"
11 caps1 = '{"platformName": "Android", "appium:deviceName": "172.16.10.103:20005", "appium:platformVersion": "7.1.2","appium:notReset": true}'
12 caps = json.loads(caps1)
13 
14 
15 driver = Remote(url, caps)
16 
17 driver.save_screenshot("打开界面的截图.png")
18 
19 # 第一步获取所有的上下文对象
20 
21 contexts = driver.contexts    # driver.context是获取所有上下文
22 print(contexts)
23 
24 current_context = driver.current_context    # driver.current_context是当前所在的上下文是哪一个
25 page_source = driver.page_source
26 print("切换之前的页面是:", current_context)
27 print("切换之前的页面源码是:之前.txt")
28 with open("之前.txt", "w", encoding='utf8') as f:
29     f.write(str(page_source))
30 
31 
32 driver.switch_to.context(contexts[-1])  # 切换上下文
33 # driver.switch_to.context() 切换上下文
34 current_context = driver.current_context
35 page_source = driver.page_source
36 print("切换之后的页面是:", current_context)
37 print("切换之后的页面源码是:之后.txt")
38 with open("之后.txt", "w", encoding='utf8') as f:
39     f.write(str(page_source))

运行结果如下:

 

contexts上下文操作
获取所有上下文
driver.contexts

获取当前上下文
driver.context

切换上下文
方法一:driver.switch_to.context('WEBVIEW_com.xkw.client')
方法二:contexts = driver.contexts
driver.switch_to.context(contexts[-1])

切回原生应用
driver.switch_to.context('NATIVE_APP')