逻辑如下:
1、获取当前所有的contexts
2、找到webview的context并切换
3、获取webview的page_source保存为html文件
4、定位html文件
5、操作完毕切换到natvice继续操作app
import unittest
from time import sleep
from appium import webdriver
from selenium.webdriver.support.wait import WebDriverWait
class WifI(unittest.TestCase):
@property
def desired_caps(self):
return {
"platformName": "Android",
"platformVersion": "5.1",
"deviceName": "Meizu",
"unicodeKeyboard": True,
"resetKeyboard": True,
"appPackage": "com.wifi.newss",
"appActivity": "com.wifi.news.ui.main.SplashActivity",
# "udid": devices['udid'],
# "app": find_apk()
}
def setUp(self):
self.driver = webdriver.Remote("http://localhost:4723/wd/hub",
self.desired_caps)
def find_element(self, loc):
"""("xpath","111121212")
self.drivers.find_element(by='xpath',value='111')
"""
try:
WebDriverWait(self.driver, 60).until(
lambda dr: self.driver.find_element(*loc).is_displayed(),
message="Driver Wait Time Out")
return self.driver.find_element(*loc)
except Exception as e:
raise ValueError(e)
def tearDown(self):
self.driver.quit()
def take_screenshot(self):
"""截图方法"""
pass
def test_news(self):
# 点击导航首页按钮
index_el = ("id", "com.wifi.newss:id/iv_user_flow_icon")
self.find_element(index_el).click()
self.take_screenshot()
# 点击推荐
el_top_nav = ("xpath",
"//android.widget.FrameLayout[1]/android.widget.LinearLayout[1]/android.widget.FrameLayout[1]/android.widget.LinearLayout[1]/android.widget.FrameLayout[1]/android.widget.RelativeLayout[1]/android.widget.LinearLayout[1]/android.widget.FrameLayout[1]/android.widget.RelativeLayout[1]/android.widget.RelativeLayout[1]/android.widget.HorizontalScrollView[1]/android.widget.LinearLayout[1]/android.widget.TextView[1]")
self.find_element(el_top_nav).click()
self.take_screenshot()
# 关注
focous_el = ("xpath",
"//android.widget.FrameLayout[1]/android.widget.LinearLayout[1]/android.widget.FrameLayout[1]/android.widget.LinearLayout[1]/android.widget.FrameLayout[1]/android.widget.RelativeLayout[1]/android.widget.LinearLayout[1]/android.widget.FrameLayout[2]/android.widget.TabHost[1]/android.widget.LinearLayout[1]/android.widget.TabWidget[1]/android.widget.RelativeLayout[2]/android.widget.ImageView[1]")
self.find_element(focous_el).click()
sleep(5)
contenss = self.driver.contexts
print("contents:{}".format(contenss))
# 获取所有的contents:['NATIVE_APP', 'WEBVIEW_com.wifi.newss']
self.driver.switch_to.context("WEBVIEW_com.wifi.newss")
# 获取webview中的html文件进行分析定位
r = self.driver.page_source
# 定位webview并操作
self.driver.find_element_by_xpath(
'//*[@id="timeline"]/div/ul/li[1]/a/div[1]/div[2]').click()
if __name__ == '__main__':
unittest.main()