python+appium,点击/id,name,关闭app等demo

本文介绍了一个基于Appium的自动化测试框架实现,包括截图管理、设备配置、元素定位等关键功能。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

# -*- coding:utf-8 -*-
import os,re,time,datetime,yaml
import logging
from appium import webdriver
import warnings


def Delete_screenshots(address):
   print('即将删除图片列表:')
   if address =='T':
      #rf调用的path地址,python调用需注释。
      path = abspath + "\screenshot"
      #python运行时使用下面代码,注释上面。
      # path = os.path.abspath(r"..") + "\screenshot"
   else:
      path = abspath + "\screenshot" + "\\" + address
   for i in os.listdir(path):
      path_file = os.path.join(path, i)
      if os.path.isfile(path_file):
         print(path_file)
         os.remove(path_file)
      else:
         for f in os.listdir(path_file):
            path_file2 = os.path.join(path_file, f)
            if os.path.isfile(path_file2):
               print(path_file2)
               os.remove(path_file2)
   print('删除成功!')




def driver():
    x = init_yaml()
    warnings.simplefilter('ignore', ResourceWarning)

    capailities = {
        'platformName': 'Android',
        'deviceName': x['deviceName'],
        'platformVersion': x['platformVersion'],
        'appPackage': x['appPackage'],
        'appActivity': x['appActivity'],
        #'unicodeKeyboard': "True",  # 使用unicode输入法
        #'resetKeyboard': "True",  # 重置输入法到初始状态
        'noReset': "True",  # 启动app时不要清除app里的原有的数据
        'noSign': "True",
        'AppWaitActivity': ' app包名.IndexActivity',
        'NewCommandOut': '180',
    }
    driver = webdriver.Remote('http://localhost:4723/wd/hub', capailities)
    driver.wait_activity(".IndexActivity",10)
    # 跳过更新弹窗
    try:
        driver.find_element_by_id(" app包名/next_btn").click()    except:
        time.sleep(1)
    return driver



def myprint(*args):
   print(*args)
   #pass


#   该方法用来确认name元素是否存在,如果存在返回flag=true,否则返回false
def isElementExist(driver,element):
    flag=True
    browser=driver
    try:
        #browser.find_element_by_css_selector(element)
        browser.find_element_by_xpath(element)
        return flag
    except:
        flag=False
        return flag

#页面寻找元素
def findItem(driver,element):
   source = driver.page_source
   if element in source:
      return True
   else:
      return False


#   该方法用来确认id元素是否存在,如果存在返回flag=true,否则返回false
def idisElementExist(driver,element):
    flag=True
    browser=driver
    try:
        #browser.find_element_by_css_selector(element)
        browser.find_element_by_id(element)
        return flag

    except:
        flag=False
        return flag

#将时分秒转换成秒
def ts(driver,t):
    h,m,s = t.strip().split(":")
    return int(h) * 3600 + int(m) * 60 + int(s)

print(ts)

def swipe_until_find_in_list(driver,ele):
    # 滚动直至找到元素
    i=0
    while(1<10):
        try:
            ele.click()  # 尝试点击元素
            break
        except:
            swipeUp(driver)
            i = i + 1
            if (i==10):
                print("没有找到元素")


#   该方法用来确认class元素是否存在,如果存在返回flag=true,否则返回false
def classisElementExist(driver,element):
    flag=True
    browser=driver
    try:
        #browser.find_element_by_css_selector(element)
        browser.find_element_by_class_name(element)
        return flag

    except:
        flag=False
        return flag


def login(driver,user,password):
    # 登录
    try:
        driver.implicitly_wait(2)
        driver.find_element_by_id("app包名/ll_me").click()
    except:
        pass
    time.sleep(1)
    username = driver.find_element_by_id("username").text
    if (username != "登录/注册"):
        logging.debug("已登录,执行登出并登录")
        time.sleep(1)
        logout(driver)
    else:
        time.sleep(1)
    driver.find_element_by_id("avatar").click()

    driver.implicitly_wait(2)
    if ("Login" not in driver.current_activity):
        raise Exception("当前页面不是登录页面")
    # 输入手机号码
    tel = driver.find_element_by_id("myEdit")
    tel.clear()
    tel.send_keys(user)
    # 输入密码
    pwd_field = driver.find_element_by_id("et_password")
    pwd_field.clear()
    pwd_field.send_keys(password)

    driver.find_element_by_id("button1").click()
    driver.implicitly_wait(3)

    driver.wait_activity(".IndexActivity",5)
    if(driver.current_activity==".IndexActivity"):
        logging.debug("登录成功")
    else:
        logging.debug("登录失败")

def logout(driver):
    #登出
    try:
        driver.implicitly_wait(2)
        driver.find_element_by_id("app包名/ll_me").click()
    except:
        pass
    username = driver.find_element_by_id("username").text
    if (username == "登录/注册"):
        logging.debug("未登录,跳过登出操作")
    else:
        driver.find_element_by_id("avatar").click()
        driver.implicitly_wait(2)
        driver.find_element_by_id("button_exit").click()
    time.sleep(1)
    if (driver.current_activity==".IndexAtivity"):
        logging.debug("登出成功")

def current_time():
    # 返回当前时间
    return datetime.datetime.now().strftime('%Y%m%d%H%M%S')

def isElementDisplayed(driver,type,ele):
    # 判断控件是否存在
    #isElementDisplayed(driver,By.ID,"my")
    #isElementDisplayed(driver,By.XPATH,"my")
    try:
        driver.find_element(by=type,value=ele)
        return True
    except:
        return False

def init_yaml():
    yamlpath = os.path.dirname(__file__) + "\element.yaml"
    #print(yamlpath)
    with open(yamlpath, encoding='utf-8') as f:
        x = yaml.load(f,Loader=yaml.Loader)
    return x

def getSize(driver):
    # 获得屏幕大小宽和高
    x = driver.get_window_size()['width']
    y = driver.get_window_size()['height']
    return (x, y)

def swipeUp(driver,t=1):
    # 手指向上滑动
    l = getSize(driver)
    x1 = int(l[0] * 0.5)    #x坐标
    y1 = int(l[1] * 0.75)   #起始y坐标
    y2 = int(l[1] * 0.25)   #终点y坐标
    driver.swipe(x1, y1, x1, y2,t*1000)

def swpeUpBySize(driver,height,t=1):
    l = getSize(driver)
    x1 = int(l[0] * 0.5)  # x坐标
    y1 = int(l[1] * 0.75)  # 起始y坐标
    y2 = int(l[1]*0.75 -height)  # 终点y坐标
    driver.swipe(x1, y1, x1, y2, t * 1000)


def swipeDown(driver,t=1):
    # 手指向下滑动
    l = getSize(driver)
    x1 = int(l[0] * 0.5)  #x坐标
    y1 = int(l[1] * 0.25)   #起始y坐标
    y2 = int(l[1] * 0.75)   #终点y坐标
    driver.swipe(x1, y1, x1, y2,t*1000)

def swipeDownBySize(driver,height,t=1):
    # 手指向下一点点
    l = getSize(driver)
    x1 = int(l[0] * 0.5)  #x坐标
    y1 = int(l[1] * 0.25)   #起始y坐标
    y2 = int(l[1] * 0.75 -height)   #终点y坐标
    driver.swipe(x1, y1, x1, y2, t*1000)

def swipLeft(driver,t=1):
    # 手指向左滑动
    l=getSize(driver)
    x1=int(l[0]*0.75)
    y1=int(l[1]*0.5)
    x2=int(l[0]*0.05)
    driver.swipe(x1,y1,x2,y1,t*1000)

def swipRight(driver,t=1):
    # 手指向右滑动
    l=getSize(driver)
    x1=int(l[0]*0.05)
    y1=int(l[1]*0.5)
    x2=int(l[0]*0.75)
    driver.swipe(x1,y1,x2,y1,t*1000)

def tap(driver,x,y,duration=500):
    # 点击坐标
    driver.tap([(x,y)],duration)

def scroll(driver,el1,el2):
    # 从元素el1滑动至元素el2
    driver.scroll(el1,el2)

<think>好的,我现在需要帮用户解决Appium启动时出现的Traceback错误,特别是Remote Webdriver初始化失败的问题。首先,我得先理解用户的问题。用户在使用PythonAppium库时,遇到了初始化Webdriver的错误,错误信息指向http://localhost:4723,可能是在连接Appium服务器时出了问题。用户提供的引用内容提到了desired_caps的设置、需要的Appium组件安装,以及可能的bug。 首先,我应该回顾常见的Appium初始化问题。根据经验,这类错误通常有几个原因:Appium服务器未启动、端口被占用、desired capabilities配置错误、设备连接问题,或者依赖的Appium服务未安装(如Appium Settings和uiautomator2 server)。 用户提到引用[2]中的bug,可能是在安装这些服务时出现了问题。我需要检查用户是否正确安装了这些服务,并且设备上已经授权USB调试。此外,查看引用[3]中的desired_caps配置是否正确,比如platformVersion、deviceName、udid是否与实际设备匹配。udid是否正确获取,可以通过adb devices命令确认。 接下来,可能的解决方案步骤包括: 1. 确保Appium服务器正在运行,并且端口4723没有被其他进程占用。用户可以尝试重启Appium服务或者更换端口。 2. 检查desired capabilities的每个参数是否正确。特别是appPackage和appActivity是否有效,udid是否正确。 3. 确认设备已正确连接,USB调试已开启,并且电脑已授权该设备。 4. 确保设备上安装了必要的Appium服务应用,如Appium Settings和uiautomator2 server,可能需要手动安装或通过Appium自动安装。 5. 查看完整的Traceback日志,确定具体的错误信息,比如是否涉及网络连接问题、证书问题,或者Appium版本不兼容。 另外,用户的环境是MAC,可能需要检查环境变量或路径设置是否正确,以及Python库的版本是否与Appium兼容。例如,AppiumPython客户端库版本是否过旧,或者与Appium服务器版本不匹配。 最后,建议用户提供具体的Traceback错误信息,以便更精准地定位问题。如果用户没有提供完整日志,可能需要指导他们如何捕获并分享详细的错误信息,包括运行时的日志输出,这有助于排除更深层次的问题,比如Appium服务器的响应内容或设备端的异常。</think>### Appium Remote Webdriver初始化失败解决方案 根据你提供的错误信息和代码片段,以下是分步排查与解决方法: --- #### 一、检查Appium服务器状态 1. **确认Appium服务已启动** 在终端执行命令启动Appium服务器: ```bash appium -p 4723 ``` 若出现端口冲突(如`4723`被占用),可更换端口: ```python # 修改代码中的URL端口 url = 'http://localhost:4724/wd/hub' ``` 2. **验证服务器连通性** 浏览器访问 `http://localhost:4723/wd/hub/status`,正常应返回JSON格式的状态信息[^3]。 --- #### 二、核对Desired Capabilities配置 对比你的配置与标准模板,常见问题包括: - **`udid`错误**:通过`adb devices`获取设备真实ID - **`appPackage/appActivity`错误**:使用`adb shell dumpsys window | grep mCurrentFocus`查看当前活动 - **平台版本不匹配**:`platformVersion`需与手机系统版本一致 修正示例: ```python desired_caps = { "platformName": "Android", "platformVersion": "11", # 必须与手机设置中的版本号完全一致 "deviceName": "VIVO", # 自定义名称不影响连接 "appPackage": "free.xxxxxxx", "appActivity": "free.xxxxx.activity.MainActivity", "udid": "7PXOSONNFQXXXX", # 必须通过adb验证 "automationName": "UiAutomator2", # 必须明确指定 "noReset": True # 避免重复安装服务 } ``` --- #### 三、设备端服务安装验证 1. **手动安装依赖APP** - 在设备上安装`Appium Settings`和`io.appium.uiautomator2.server`的APK文件(可从[Appium GitHub仓库](https://github.com/appium)下载) - 开启设备**开发者选项**中的USB调试和安装权限 2. **检查服务运行状态** ```bash adb shell pm list packages | grep 'appium' ``` 应显示`io.appium.uiautomator2.server`等包名[^2]。 --- #### 四、完整错误排查流程 1. **获取详细日志** 在代码中添加参数获取完整日志: ```python from appium import webdriver driver = webdriver.Remote(url, desired_caps, keep_alive=True) ``` 2. **常见错误对照表** | 错误现象 | 解决方案 | |---|---| |`NewCommandTimeoutError`| 增加`newCommandTimeout`参数值 | |`Unable to find a device`| 检查USB连接和`udid`配置 | |`Failure [INSTALL_FAILED_UPDATE_INCOMPATIBLE]`| 卸载设备上已有的Appium服务APP | --- #### 五、环境验证脚本 ```python import subprocess # 验证adb连接 adb_status = subprocess.getoutput("adb devices") print(f"ADB设备列表:\n{adb_status}") # 验证Appium服务 try: driver = webdriver.Remote(url, desired_caps) print(driver.current_package) except Exception as e: print(f"完整错误堆栈:\n{str(e)}") finally: driver.quit() ``` ---
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

linmumum

吃饱睡

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值