def init_pwd(): driver = Remote(desired_capabilities=devices_info.caps) driver.implicitly_wait(30) # 初始化登录页面 login = Login(driver) home = Home(driver) pwd = Pwd(driver) yield driver, login, home, pwd driver.quit()
def create() -> Optional['AppDriver']: """ Initializes appium driver :type device_name: name of the device to be used, if it is none, it uses adb command to fetch it """ try: 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.info("Finding android device") if "device_name" not in g.kwargs or g.kwargs["device_name"] is None: adb_path = os.path.join(os.environ.get('ANDROID_HOME'), 'platform-tools', "adb.exe") adb_ouput = subprocess.check_output([adb_path, "devices"]).decode('utf-8') device_name = re.search(r'^(.+)\tdevice', adb_ouput, flags=re.MULTILINE).group(1) if run_server: def appium_logging(): g.logger.info("launching appium server on {}".format(port)) try: appium_process = subprocess.Popen(shlex.split("appium --port {}".format(port)), stdout=subprocess.PIPE, shell=True) appium_logs = logging.getLogger('appium') while g.system.status > -1: line = appium_process.stdout.readline().decode('utf-8') appium_logs.debug(line) appium_process.stdout.close() appium_process.kill() except FileNotFoundError: logging.error("Appium not installed") threading.Thread(target=appium_logging).start() g.logger.info("Connecting to appium with {}".format(device_name)) desired_caps = { 'platformName': 'Android', 'deviceName': device_name, 'appPackage': 'com.whatsapp', 'appActivity': 'com.whatsapp.HomeActivity', 'noReset': 'true' } driver = Remote('http://localhost:{}/wd/hub'.format(port), desired_caps) driver.implicitly_wait(5) g.logger.info("driver created") return AppDriver(driver) except FileNotFoundError: logging.error("Device not found; make sure device is connected using `adb devices` command")
def app_driver_qcd(): caps = { "platformName": "Android", "platformVersion": "5.1", "deviceName": "Android Emulator", "appActivity": "com.xxzb.fenwoo.activity.addition.WelcomeActivity", "appPackage": "com.xxzb.fenwoo", "noReset": "False" } android_driver = Remote(desired_capabilities=caps) android_driver.implicitly_wait(10) return android_driver
def driver(): """启动和结束appium 对象""" caps = { "platformName": "Android", "automationName": "Uiautomator2", # 使用toast弹框必须要使用uiautomator2 才能定位 "deviceName": "emulator-5554", "appPackage": "com.lemon.lemonban", "appActivity": "com.lemon.lemonban.activity.WelcomeActivity" } # 创建一个会话 session = Remote(command_executor='http://127.0.0.1:4723/wd/hub', desired_capabilities=caps) # 等待 session.implicitly_wait(10) yield session
def init_app(): caps = { "platformName": "Android", "deviceName": "Android Emulator", "automationName": "UiAutomator2", "appActivity": ".activity.MainActivity", "appPackage": "com.lemon.lemonban", "chromedriverExecutableDir": r"C:\chromdriver", "noReset": False, } driver = Remote(desired_capabilities=caps, command_executor="http://127.0.0.1:4723/wd/hub") # 元素等待 driver.implicitly_wait(20)
def app_driver_nmb(): caps = { "platformName": "Android", "platformVersion": "5.1", "deviceName": "Android Emulator", "automationName": "UIAutomator2", "appActivity": "com.lemon.lemonban.activity.WelcomeActivity", "appPackage": "com.lemon.lemonban", "noReset": "False" } android_driver = Remote(desired_capabilities=caps) android_driver.implicitly_wait(10) return android_driver
def init_settings(): global drivers global capabilities global case_list global user_table global email_sign_table with codecs.open(__config_dir+'/logging.yaml','r',"utf-8") as config_open: logging_config = load(config_open) logging_config.setdefault("version",1) logging_config["handlers"]["file"]["filename"]=__log_dir+"\\"+logging_config["handlers"]["file"]["filename"] dictConfigClass(logging_config).configure() logger.debug("load config.yaml") with codecs.open(__config_dir + '/config.yaml','r','utf-8') as cfp: config = load(cfp) config.setdefault("version",1) capabilities = config["devices"] case_list = config["case_list"] logger.debug("load emailsigntable.csv file") csv.register_dialect('idialect',delimiter='|', quoting=csv.QUOTE_ALL) with codecs.open(__config_dir + '/emailsigntable.csv', 'r', 'utf-8') as efp: ret = csv.reader(efp,dialect='idialect') email_sign_table = Queue() for i in ret: if not i[0].startswith("#"): email_sign_table.put(i) # email_sign_table = Iqueue([i for i in ret if not i[0].startswith("#")]) logger.debug("load usertable.csv file") with codecs.open(__config_dir + '/usertable.csv', 'r', 'utf-8') as ufp: ret = csv.reader(ufp,dialect='idialect') user_table = Queue() for i in ret: if not i[0].startswith("#"): user_table.put(i) # user_table = Iqueue([i for i in ret if not i[0].startswith("#")]) logger.debug("init drivers...") drivers = [] for capabilitie in capabilities: driver = Remote("http://127.0.0.1:4723/wd/hub",desired_capabilities=capabilitie) driver.implicitly_wait(0.001) drivers.append(driver)
def init_app(): """启动app fixture""" # caps = { # "platformName": "Android", # "deviceName": "Android Emulator", # "automationName": "UiAutomator2", # "appActivity": ".activity.MainActivity", # "appPackage": "com.lemon.lemonban", # "chromedriverExecutableDir" : r"C:\chrome_driver", # "noReset": False, # } driver = Remote(desired_capabilities=caps, command_executor='http://127.0.0.1:4723/wd/hub') driver.implicitly_wait(20) yield driver print("退出浏览器") driver.quit()
from appium.webdriver.common.multi_action import MultiAction import time from appium.webdriver import Remote from appium.webdriver.common.touch_action import TouchAction from selenium.webdriver.common.by import By caps = { "platformName": "Android", "deviceName": "emulator-5554", "appPackage": "com.lemon.lemonban", "appActivity": "com.lemon.lemonban.activity.WelcomeActivity" } # 创建一个会话 driver = Remote(command_executor='http://127.0.0.1:4723/wd/hub', desired_capabilities=caps) # 等待 driver.implicitly_wait(10) # toast 弹框定位文本,方法一:通过 text文本定位 toast弹框 text = '用户名或者密码不正确' driver.find_element(By.XPATH, f'//*[contains(@text,"{text}")]') # 方法二: //Android.widget.Toast el = driver.find_element(By.XPATH, '//android.widget.Toast') # 断言 获取文本 el.text
from appium.webdriver.common.mobileby import MobileBy from appium.webdriver.common.touch_action import TouchAction from common.app_operate import AppOperate caps = { "platformName": "Android", "platformVersion": "5.1", "deviceName": "Android Emulator", "appActivity": "com.xxzb.fenwoo.activity.addition.WelcomeActivity", "appPackage": "com.xxzb.fenwoo", "noReset": "False" } android_driver = Remote(desired_capabilities=caps) android_driver.implicitly_wait(10) app_action = TouchAction(android_driver) app_opre = AppOperate(android_driver) # # time.sleep(2) # for i in range(4): # app_opre.swipe_left() # time.sleep(1) # # # 点击立即体检进入首页 # # android_driver.find_element_by_id("com.xxzb.fenwoo:id/btn_start").click() # # android_driver.find_element_by_android_uiautomator( # 'new UiSelector().resourceId("com.xxzb.fenwoo:id/btn_start")').click()
from appium.webdriver.common.touch_action import TouchAction import time desired_cap = { "platformName": "Android", "platformVersion": "8.0.0", "automationName": "UiAutomator2", "deviceName": "HUAWEIP30", "appPackage": "com.lemon.lemonban", "appActivity": "com.lemon.lemonban.activity.WelcomeActivity", 'noReset': True } driver = Remote(command_executor='http://127.0.0.1:4723/wd/hub', desired_capabilities=desired_cap, ) driver.implicitly_wait(15) # 获取屏幕大小 size = driver.get_window_size() # 点击题库 driver.find_element_by_id('com.lemon.lemonban:id/navigation_tiku').click() time.sleep(2) t1 = TouchAction(driver) t1.press(x=size["width"] * 0.5, y=size["height"] * 0.8) t1.wait(200) t1.move_to(x=size["width"] * 0.5, y=size["height"] * 0.7) t1.wait(200) t1.move_to(x=size["width"] * 0.5, y=size["height"] * 0.6) t1.wait(200)
"noReset": "false", } driver = Remote(desired_capabilities=caps, command_executor="http://127.0.0.1:4723/wd/hub") # driver.find_element_by_accessibility_id() # TODO: java 当中要用双引号表示字符串 # new UiSelector().className(\"android.widget.FrameLayout\").resourceId(\"com.lemon.lemonban:id/navigation_my\").clicable() # driver.find_element_by_android_uiautomator('new UiSelector().className(\"android.widget.FrameLayout\").resourceId(\"com.lemon.lemonban:id/navigation_my\")') #查找元素方式 #driver.find_element #元素等待 driver.implicitly_wait(20) windown_size = driver.get_window_size() print(windown_size) time.sleep(5) #滑动,需要滑动3次 for i in range(3): driver.swipe(800, 500, 10, 500) time.sleep(0.2) #点击立即进入 #driver.find_element_by_id('com.xxzb.fenwoo:id/btn_start') #java的写法uiautomator start_btn = driver.find_element_by_android_uiautomator( 'new UiSelector().resourceId("com.xxzb.fenwoo:id/btn_start")') start_btn.click()
class Client: def __init__(self): super(Client, self).__init__() self.config = Config() self.desired_caps = { 'platformName': self.config.get_config('DESIRED_CAPS', 'platformName'), 'platformVersion': self.config.get_config('DESIRED_CAPS', 'platformVersion'), 'deviceName': self.config.get_config('DESIRED_CAPS', 'deviceName'), 'appPackage': self.config.get_config('DESIRED_CAPS', 'appPackage'), 'appActivity': self.config.get_config('DESIRED_CAPS', 'appActivity'), # 'udid': '127.0.0.1:4723', 'unicodeKeyboard': True, 'resetKeyboard': True, 'autoGrantPermissions': True, 'automationName': 'uiautomator2', 'app': PATH("packages/apps-release.apk") } self.driver_url = self.config.get_config('APP_DATABASE', 'driver_url') # self.driver = Remote("http://127.0.0.1:4723/wd/hub", self.desired_caps) self.driver = Remote('{}'.format(self.driver_url), self.desired_caps) self.driver.implicitly_wait(15) self.wait = WebDriverWait def find(self, xpath): result = self.driver.find_element_by_xpath(xpath).text return result def click(self, res): try: self.driver.find_element_by_id(res).click() except: self.driver.find_element_by_xpath(res).click() def xpath(self, xpath): self.driver.find_element_by_xpath(xpath).click() def send_keys(self, res, keywords): try: self.driver.find_element_by_id(res).send_keys(keywords) except: self.driver.find_element_by_xpath(res).send_keys(keywords) def swipe(self, res): width = self.driver.get_window_rect()['width'] height = self.driver.get_window_rect()['height'] i = 0 while i < 10: try: self.driver.find_element_by_id(res).is_enabled() break except Exception as e: self.driver.swipe(width / 2, height * 0.8, width / 2, height * 0.2) i = i + 1
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})