Appium 解决微信公众号、小程序切换 webview 后无法定位元素的问题

如何切换webview进入小程序请参考https://testerhome.com/topics/12003

脚本思路:
进入webview后会存在多个handle同Web页签一样,获取所有的handle,然后在遍历所有的handle,通过switch_to_window进行handle切换,当某个handle可以定位到我们需要定位的元素时,然后我们就可以进行之后的自动化操作了!

  1.  
    <code style="font-family:Menlo, Monaco, Consolas, 'Courier New', monospace;line-height:18px;font-size:12px;color:rgb(68,68,68);border:none;">#coding=utf-8
  2.  
    from appium import webdriver
  3.  
    import time,os,re
  4.  
    from appium.webdriver.common.touch_action import TouchAction
  5.   
  6.   
  7.  
    desired_caps = {}
  8.  
    desired_caps['platformName'] = 'Android'
  9.  
    desired_caps['deviceName'] = 'Android001'
  10.  
    desired_caps['unicodeKeyboard'] = True
  11.  
    desired_caps["resetKeyboard"] = True
  12.  
    desired_caps["newCommandTimeout"]=30
  13.  
    desired_caps['fullReset'] = 'false'
  14.  
    desired_caps['appPackage'] = 'com.tencent.mm'
  15.  
    desired_caps['appActivity'] = 'com.tencent.mm.ui.LauncherUI'
  16.  
    desired_caps['recreateChromeDriverSessions'] = True
  17.  
    desired_caps['noReset'] = True
  18.  
    desired_caps['newCommandTimeout'] = 10
  19.  
    desired_caps['chromeOptions']={'androidProcess': 'com.tencent.mm:appbrand0'}
  20.  
    driver = webdriver.Remote(command_executor = 'http://127.0.0.1:4723/wd/hub',desired_capabilities = desired_caps)
  21.  
    time.sleep(2)
  22.  
    time.sleep(1)
  23.  
    driver.implicitly_wait(10)
  24.  
    driver.find_element_by_name('发现').click()
  25.  
    time.sleep(1)
  26.  
    driver.swipe(100,1200,100,900)
  27.  
    driver.find_element_by_name('小程序').click()
  28.  
    driver.find_element_by_name('美团外卖').click()
  29.  
    time.sleep(2)
  30.  
    contexts = driver.contexts
  31.  
    print contexts
  32.  
    time.sleep(2)
  33.  
    driver.switch_to.context('WEBVIEW_com.tencent.mm:appbrand0')
  34.  
    print '切换成功'
  35.  
    print driver.current_context
  36.  
    all_handles = driver.window_handles
  37.  
    print len(all_handles)
  38.  
    for handle in all_handles:
  39.  
    try:
  40.  
    driver.switch_to_window(handle)
  41.  
    print driver.page_source
  42.  
    driver.find_element_by_css_selector('.filter-select.flex-center') #定位“筛选 ”按钮
  43.  
    print '定位成功'
  44.  
    break
  45.  
    except Exception as e:
  46.  
    print e
  47.  
    driver.find_element_by_css_selector('.filter-select.flex-center').click()
  48.  
    time.sleep(5)
  49.  
    driver.quit()</code>

原本:https://blog.csdn.net/qq_35741999/article/details/79430077

posted @ 2018-10-03 17:01  peachlf  阅读(1710)  评论(0编辑  收藏  举报