Exemplo n.º 1
0
class Base:
    caps = {
        "platformName": "Android",
        "platformVersion": "6.0",
        "deviceName": "192.168.56.101:5555",
        "appPackage": "com.xueqiu.android",  # aapt dump badging apk
        "appActivity": "com.xueqiu.android.view.WelcomeActivityAlias",
        "noReset": False
    }

    def __init__(self, duration):
        self.driver = Remote(
            desired_capabilities=self.caps,
            command_executor='http://127.0.0.1:4723/wd/hub')  # 初始化caps
        self.duration = 1000  # 滑动持续时间,单位毫秒,默认None(一般设置500-1000毫秒比较合适)

    def Screenshots(self, save_file_name):
        """
        截图(待完善)
        :param save_file_name: 保存的地址
        :return:
        """
        self.driver.get_screenshot_as_file(save_file_name)

    def find_element(self, locator):
        """
        单个元素定位
        :param locator: 定位器
        :return: 定位到的元素
        """
        try:
            ele = WebDriverWait(self.driver, timeout=20).until(
                EC.presence_of_element_located(locator))
            return ele
        except Exception as e:
            self.Screenshots(
                "/Users/xiaoff/python/2020_study/appium/封装框架/screen_shot/定位问题.png"
            )
            return '未定到到该元素', e

    def find_elements(self, locator):
        """
        元素定位有多个值
        :param locator: 定位器
        :return:
        """
        try:
            ele = WebDriverWait(self.driver, timeout=20).until(
                EC.presence_of_all_elements_located(locator))
            return ele
        except Exception as e:
            self.Screenshots(
                "/Users/xiaoff/python/2020_study/appium/封装框架/screen_shot/定位问题.png"
            )
            return '未定到到该元素', e

    """----滑动-----"""

    def get_width(self):
        """
        获取屏幕的宽度
        :return:
        """
        width = self.driver.get_window_size()['width']
        return width

    def get_height(self):
        """
        获取屏幕的高度
        :return:
        """
        height = self.driver.get_window_size()['height']
        return height

    def swipe_to_right(self):
        """
Exemplo n.º 2
0
 def __init__(self, duration):
     self.driver = Remote(
         desired_capabilities=self.caps,
         command_executor='http://127.0.0.1:4723/wd/hub')  # 初始化caps
     self.duration = 1000  # 滑动持续时间,单位毫秒,默认None(一般设置500-1000毫秒比较合适)
Exemplo n.º 3
0
from appium.webdriver import Remote
import time

from appium.webdriver.common.mobileby import MobileBy

desired_cap = {
    "platformName": "Android",
    "platformVersion": "8.0.0",
    "automationName": "UiAutomator2",
    "deviceName": "HUAWEIP30",
    "appPackage": "com.lemon.lemonban",
    "appActivity": "com.lemon.lemonban.activity.WelcomeActivity"
}

driver = Remote(command_executor='http://127.0.0.1:4723/wd/hub',
                desired_capabilities=desired_cap)
driver.implicitly_wait(15)
driver.find_element_by_android_uiautomator(
    'new UiSelector().text("我的柠檬")').click()
time.sleep(3)
driver.find_element_by_android_uiautomator(
    'new UiSelector().text("点击头像登录")').click()
driver.find_element_by_android_uiautomator(
    'new UiSelector().text("手机号码")').send_keys('15011466717')
driver.find_element_by_android_uiautomator(
    'new UiSelector().text("密码")').send_keys('15011466717')

driver.find_element_by_android_uiautomator(
    'new UiSelector().text("登录")').click()

# 获取tost提示
Exemplo n.º 4
0
    def create() -> Optional['AppDriver']:
        """
        Initializes appium driver
        """
        # region input from kwargs
        # todo fix repetition of kwarg code
        run_server = not ("no_server" in g.kwargs and g.kwargs["no_server"])

        if "port" in g.kwargs and g.kwargs["port"] is not None:
            port = g.kwargs["port"]
        elif run_server:
            port = str(helper.get_free_tcp_port())
        else:
            port = "4723"

        g.logger.debug("Finding android device")

        if "device_name" in g.kwargs and g.kwargs["device_name"] is not None:
            device_name = g.kwargs["device_name"]
        elif "device" in g.kwargs and g.kwargs["device"] is not None:
            device_name = g.kwargs["device"]
        else:
            if 'ANDROID_HOME' not in os.environ.keys():
                g.logger.error("`ANDROID_HOME` environment variable not found "
                               "(default: %USERPROFILE%\AppData\Local\Android\Sdk)")
                raise
            adb_path = os.path.join(os.environ.get('ANDROID_HOME'), 'platform-tools', "adb")
            try:
                ada_output = subprocess.check_output([adb_path, "devices"]).decode('utf-8')
            except FileNotFoundError:
                g.logger.error("`ANDROID_HOME` environment variable not setup correctly "
                               "(default: %USERPROFILE%\AppData\Local\Android\Sdk)")
                raise
            search = re.search(r'^(.+)\tdevice', ada_output, flags=re.MULTILINE)
            if search is None:
                g.logger.error("No Android Device Found, Either specify using `device` "
                               "or make sure a device is available in adb")
                raise DeviceNotFound
            device_name = search.group(1)

        if "check_wait" in g.kwargs and g.kwargs["check_wait"] is not None:
            implicit_wait = g.kwargs["check_wait"]
        else:
            implicit_wait = 5

        # endregion

        appium_thread = None
        if run_server:
            def appium_logging():
                g.logger.debug("launching appium server on {}".format(port))
                try:
                    g.appium_process = subprocess.Popen(shlex.split(f"appium --port {port}"),
                                                        stdout=subprocess.PIPE, shell=True)
                    appium_logs = logging.getLogger('appium')
                    while g.system.status > -1:
                        line = g.appium_process.stdout.readline().decode('utf-8')
                        appium_logs.debug(line)
                    g.appium_process.stdout.close()
                    g.appium_process.kill()
                    g.system.status = -2
                    g.logger.debug("appium server closed")
                except FileNotFoundError:
                    g.logger.error("Appium not installed, install node package manager, "
                                   "then use this command to install `npm install -g [email protected]`")
                    raise

            appium_thread = threading.Thread(target=appium_logging)
            appium_thread.start()

        g.logger.debug("Connecting to appium with {}".format(device_name))
        desired_caps = {
            "platformName": "Android",
            "udid": device_name,
            "appPackage": "com.whatsapp",
            "appActivity": "com.whatsapp.HomeActivity",
            "noReset": "true",
            "deviceName": "Android Emulator"
        }
        try:
            driver = Remote('http://localhost:{}/wd/hub'.format(port), desired_caps)
        except WebDriverException as e:
            if "JAVA_HOME is not set currently" in e.msg:
                g.logger.error("`JAVA_HOME` environment variable not setup correctly "
                               "(default C:\PROGRA~1\Java\jdk1.8.0_181)")
            else:
                g.logger.error("Appium server could not be started because of unknown exception, please refer "
                               "'appium.log' file to troubleshoot. Alternatively you can run appium server as a "
                               "standalone and use `no_server` parameter. Refer Supbot2 docs for more info.")

            if not g.appium_process:
                g.appium_process.stdout.close()
                g.appium_process.kill()
            raise

        driver.implicitly_wait(1)
        g.logger.debug("driver created")
        return AppDriver(driver, implicit_wait, appium_thread, {"port": port, "device": device_name})
Exemplo n.º 5
0
# -*- coding:utf-8 -*-
# from yaml import load
# import re
from appium.webdriver import Remote
caps = {
    'platformName': 'Android',  # 操作系统
    'platformVersion': 5.1,  # 版本
    'deviceName': 'Android Emulator',
    'appActivity': 'com.xxzb.fenwoo.activity.addition.WelcomeActivity',  # 入口
    'appPackage': 'com.xxzb.fenwoo',  # 包名
    # 'app':r'E:\V1.2.2\app-release.apk',                        # 文件路径
    'automationName': 'UiAutomator2',
    'noReset': False
}  # 重置
driver = Remote(desired_capabilities=caps)

mg = driver.current_activity
print(mg)
# path=r'D:\pycharm-professional-2019.1.1\APP\qianchengdaiapp_V2\a.yaml'
# m=load(open(path))
#
# print(m)

# s='可用余额35451.48元'
#
# p = '[1-9][0-9]+'
#
# m=re.search(p,s).group()
# print(m)
#
# s='34,301.05'
Exemplo n.º 6
0
caps = {
    "platformName": "Android",
    "platformVersion": "6.0",
    "deviceName": "emulator-5554",
    "appPackage": "com.xueqiu.android",  # aapt dump badging apk
    "appActivity": "com.xueqiu.android.view.WelcomeActivityAlias",
    "noReset": False
}

from appium.webdriver import Remote

driver = Remote(desired_capabilities=caps,
                command_executor='http://127.0.0.1:4723/wd/hub')  # 初始化Remote

# Android only  模拟物理按键:返回 拍照 电源 拨号  音量加减
driver.press_keycode(24)  # 按键号
driver.get_screenshot_as_file("保存后的文件名")  # 截屏
driver.background_app("秒")  # 将应用放在后台多长时间 -1:一直置于后台;
driver.lock()  # 锁屏
driver.unlock()  # 解锁