Python+Appium+unittest输入具体日期来滚动选择日期

问题:

对应APP应用,如果有滚动选择日期(滚动选择其他选项也是一样),然后想直接输入一个日期,格式为“xxxx-xx-xx”,然后找到实现滚动选择到所输入的日期,怎么办呢

 

 

 

下面是我的解决办法,直接上代码吧(方法一):

    def test_04_DataReport(self,device="77250569",date="2018-1-28"):
        timewait=5
        datelist = date.split('-')
        #now=datetime.datetime.now().strftime('%Y-%m-%d')
        #nowlist=now.split('-')
        #yeardiff=int(nowlist[0])-int(datelist[0])
        #monthdiff=int(nowlist[1])-int(datelist[1])
        #daydiff=int(nowlist[2])-int(datelist[2])
        driver = self.driver
        assertelement = LotteryTests.isElementExist(self, "id=com.dgcy.paysx:id/more_t")#判断数据报表元素是否可见
        if assertelement:
            print("已登录在APP首页".decode("utf-8"))
        else:
            self.test_01_login()#如果不在APP首页则重新登录
        driver.find_element_by_id("com.dgcy.paysx:id/more_t").click()  # 点击数据报表
        WebDriverWait(driver, timewait).until(lambda x: x.find_element_by_id("com.dgcy.paysx:id/tickets_detail_group"))  # 等待数据报表页面可见
        driver.find_element_by_id('com.dgcy.paysx:id/tickets_detail_group').click()  # 点击所有设备下拉框
        WebDriverWait(driver, 5).until(lambda x: x.find_element_by_id("android:id/text1"))  # 等待显示下拉栏所有数据

        driver.find_element_by_android_uiautomator('new UiSelector().clickable(true).text("%s")'% device) .click()  # 点击下拉框所输入的设备
        print("选择的设备编号为:".decode("utf-8") + device)
        time.sleep(1)
        driver.find_element_by_id('com.dgcy.paysx:id/endTime_bt').click()  # 点击日期选择
        eleyear=driver.find_elements_by_id('android:id/numberpicker_input')[0]#当前年份元素
        beforeB=driver.find_elements_by_class_name('android.widget.Button')[0].size#获取上一格的尺寸
        currentyear=eleyear.text#获取当前默认年份
        #Ybounds=eleyear.size#获取年份的元素尺寸,年月日的高度都是一样的
        Ybounds0 = eleyear.location#获取年份的起始位置
        singlebounds = beforeB['height']  # 滑动一格的长度
        print("滑动的长度为:".decode("utf-8")+str(singlebounds))
        #print(Ybounds)
        print("起始坐标:".decode("utf-8")+str(Ybounds0))
        x1 = Ybounds0['x']  # 年份起始横坐标
        y1 = Ybounds0['y']  # 年份起始纵坐标
        yeardiff = int(currentyear) - int(datelist[0]) #当前年份和所选年份之差
        if str(yeardiff).count('-')==1 and str(yeardiff)[0] == '-':
            y2 = Ybounds0['y']-singlebounds#如果年份之差为负数则向上滑动
            swipecount=int(str(yeardiff)[1])
        else:
            y2 = singlebounds + Ybounds0['y']  #如果年份之差为负数则向下滑动
            swipecount = yeardiff
        if swipecount > 0:
            for i in range(0,swipecount):
                eleyear.click()
                driver.swipe(x1, y1, x1, y2)  # 年份滑动一格
                if eleyear.text == str(int(datelist[0])) :
                    print("输入日期正确:".decode("utf-8")+eleyear.text+"".decode("utf-8"))
                    break
        else:
            print("输入日期正确:".decode("utf-8") + eleyear.text + "".decode("utf-8"))
        #print(eleyear.text)
        elemonth = driver.find_elements_by_id('android:id/numberpicker_input')[1]  # 当前月份元素
        currentmonth = elemonth.text  # 获取当前默认月份
        #Mbounds = elemonth.size  # 获取月份的元素尺寸,年月日的高度都是一样的
        Mbounds0 = elemonth.location  # 获取月份的起始位置
        x1 = Mbounds0['x']  # 月份起始横坐标
        y1 = Mbounds0['y']  # 月年份起始纵坐标
        monthdiff = int(currentmonth) - int(datelist[1])  # 当前月份和所选月份之差
        if str(monthdiff).count('-') == 1 and str(monthdiff)[0] == '-':
            y2 = Mbounds0['y'] - singlebounds  # 如果月份之差为负数则向上滑动
            swipecount = int(str(monthdiff)[1])
        else:
            y2 = singlebounds + Mbounds0['y']  # 如果月份之差为负数则向下滑动
            swipecount = monthdiff
        if swipecount>0:
            for i in range(0,swipecount):
                elemonth.click()
                driver.swipe(x1, y1, x1, y2)  # 月份滑动一格
                if elemonth.text == str(int(datelist[1])) :
                    print("输入日期正确:".decode("utf-8") + elemonth.text+"".decode("utf-8"))
                    break
        else:
            print("输入日期正确:".decode("utf-8") + elemonth.text + "".decode("utf-8"))
        #print(elemonth.text)
        eleday = driver.find_elements_by_id('android:id/numberpicker_input')[2]  # 当前日元素
        currentday = eleday.text  # 获取当前默认日
        #Dbounds = eleday.size  # 获取日的元素尺寸,年月日的高度都是一样的
        Dbounds0 = eleday.location  # 获取日的起始位置
        x1 = Dbounds0['x']  # 日起始横坐标
        y1 = Dbounds0['y']  # 日份起始纵坐标
        daydiff = int(currentday) - int(datelist[2])  # 当前日和所选日之差
        if str(daydiff).count('-') == 1 and str(daydiff)[0] == '-':
            y2 = Dbounds0['y'] - singlebounds  # 如果日之差为负数则向上滑动
            swipecount = int(str(daydiff)[1])
        else:
            y2 = singlebounds + Dbounds0['y']  # 如果日之差为负数则向下滑动
            swipecount = daydiff
        if swipecount > 0:
            for i in range(0,swipecount):
                eleday.click()
                driver.swipe(x1, y1, x1, y2)  # 日滑动一格
                if str(eleday.text) == str(datelist[2]) :
                    print("输入日期正确:".decode("utf-8") + eleday.text+"".decode("utf-8"))
                    break
        else:
            print("输入日期正确:".decode("utf-8") + eleday.text + "".decode("utf-8"))
        #print(eleday.text)
        driver.find_elements_by_id('com.dgcy.paysx:id/date_picker_ok')#点击确定
        driver.find_elements_by_id('com.dgcy.paysx:id/search_adv')  # 点击查询

 

方法二:

driver.find_element_by_id('com.dgcy.paysx:id/endTime_bt').click()  # 点击日期选择
        eles=driver.find_elements_by_id('android:id/numberpicker_input')
        eles[0].clear()#清除年份
        eles[0].send_keys(datelist[0])#重新输入年份
        text=eles[0].text
        print("选择的年份为:".decode("utf-8")+text)
        eles[1].clear()  # 清除月份
        eles[1].send_keys(datelist[1])  # 重新输入月份
        text = eles[1].text
        print("选择的月份为:".decode("utf-8") + text)
        eles[2].clear()  # 清除日份
        eles[2].send_keys(datelist[2])  # 重新输入日份
        text = eles[2].text
        print("选择的日份为:".decode("utf-8") + text)

 

方法一的思路就是先做出滑动一格的效果,然后默认年份与所输入的年份相减,如果为正的话循环向下滑动,如果为负则循环向上滑动,滑动格数为相减的绝对数。

方法二的思路是直接清除元素的text(输入框标签为input),然后直接输入想要滑动的日期。

顺便把全部代码也附上吧

import unittest
import time
import datetime
from appium import webdriver
#from HtmlTestRunner import HTMLTestRunner
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.action_chains import ActionChains
import sys
reload(sys)
sys.setdefaultencoding('utf8')
count = 0
login = {
    "username":"18520836380",
    "userpwd":"123456",
    "newsever":"http://192.168.0.112:9988/agent_client"
}
startime=time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())

class LotteryTests(unittest.TestCase):
    def setUp(self):
        #初始化测试平台
        desired_caps = {
            'platformName': 'Android',      #移动操作平台
            'platformVersion': '4.4.2',  # 移动操作系统版本
            'newCommandTimeout': '3600',  # 自定义超时时间
            'deviceName': '127.0.0.1:62001',#设备名称
            'appPackage': 'com.dgcy.paysx',  # 测试APP的包名
            'app':'E://sx_station_pay_android.apk',
            'appActivity': 'com.dgcy.pay.ui.activity.StartTicketsActivity',# 要从包中启动的Android活动的活动名称
           'automationName': 'Appium',     #自动化引擎
            # 'unicodeKeyboard':True,
            # 'resetKeyboard':True,
            'noReset':True,
            'chromeOptions':{'androidProcess': 'com.dgcy.paysx'}
        }
        print(startime+': 打开APP...'.decode("utf-8"))
        self.driver = webdriver.Remote('http://127.0.0.1:4723/wd/hub',desired_caps)
        time.sleep(5)


    def isElementExist(self, locator):
        """
        locator: locator输入规则:元素属性名=元素属性值,如果是id则以"id=xxx",如果是css则以“css=xxx”等,例如:id=com.dgcy.paysx:id/monitor_t;css=div.popup-content;
        xpath=//div[text()='删除成功'];name=myna;class=mmv;link=登录;
        :return: 布尔值
        """
        list=locator.split('=')
        flag = True
        browser = self.driver

        try:
            if list[0] == "id":
                browser.find_element_by_id(list[1])
            elif list[0] == "xpath":
                browser.find_element_by_xpath(list[1])
            elif list[0] == "name":
                browser.find_element_by_namne(list[1])
            elif list[0] == "css":
                browser.find_element_by_css_selector(list[1])
            elif list[0] == "class":
                browser.find_element_by_class_name(list[1])
            elif list[0] == "tag":
                browser.find_element_by_tag_name(list[1])
            elif list[0] == "link":
                browser.find_element_by_link_text(u"%s" % list[1])
            return flag
        except:
            flag = False
            return flag

    #def test_01_login(self): #打开app并判断是否自动登录
    #   print("Start test1...open application")
    #   time.sleep(2)
    #   #判断是否需要登录
    #   driver = self.driver
    #   assertelement=LotteryTests.isElementExist(self,"id=com.dgcy.paysx:id/monitor_t")
    #   if not assertelement:#
    #       loging = driver.find_element_by_id("com.dgcy.paysx:id/login_submit").text
    #       try:
    #           assert '登录' in loging     #检测到登录按钮
    #           print("检测到登录按钮,重新登录....")
    #           #输入用户名
    #           driver.find_element_by_id("com.dgcy.paysx:id/loginUserName").send_keys(login["username"])
    #           #输入密码
    #           driver.find_element_by_id("com.dgcy.paysx:id/loginPwd").send_keys(login["userpwd"])
    #           #输入服务器设置
    #           driver.find_element_by_id("com.dgcy.paysx:id/fwurl").send_keys(login["newsever"])
    #           time.sleep(1)
    #           #点击登录
    #           driver.find_element_by_id("com.dgcy.paysx:id/login_submit").click()
    #       except AssertionError as e:
    #           print("未检测到登录按钮....")
    #   else:
    #       print("已登录在APP首页")
    #   time.sleep(2)#
    #def test_02_firstPage(self):
    #   # 检测‘实时订单’
    #   driver = self.driver
    #   count=10
    #   assertelement = LotteryTests.isElementExist(self, "id=com.dgcy.paysx:id/monitor_t")
    #   if assertelement:
    #       firstPage = driver.find_element_by_id("com.dgcy.paysx:id/index_t").text
    #       # 添加断言是否显示“实时订单”
    #       try:
    #           assert '实时订单' in firstPage
    #           print("Login User is Right!")
    #       except AssertionError as e:
    #           print('loginUser is Error')
    #           self.test_01_login()   #非‘实时订单’则重新登录
    #   else:
    #       self.test_01_login()
    #   while count == 0:
    #       driver.find_element_by_id("com.dgcy.paysx:id/tickets_detail_group").click()#点击下拉按钮
    #       WebDriverWait(driver, 5).until(lambda x: x.find_element_by_id("android:id/text1"))#等待显示下拉栏所有数据
    #       driver.find_element_by_android_uiautomator("new UiSelector().index(0)").find_element_by_id("android:id/text1").click()
    #       for i in range(9):
    #           driver.find_element_by_id("com.dgcy.paysx:id/tickets_detail_group").click()
    #           time.sleep(1)
    #           driver.find_elements_by_id('android:id/text1')[i].click()
    #           time.sleep(9)

    #def test_03_allTicket(self):
    #    # 检测‘运营监控’
    #    timewait=5
    #    driver = self.driver
    #    assertelement = LotteryTests.isElementExist(self, "id=com.dgcy.paysx:id/monitor_t")
    #    if assertelement:
    #        firstPage = driver.find_element_by_id("com.dgcy.paysx:id/monitor_t").text
    #        # 添加断言是否显示“运营监控”
    #        try:
    #            assert '运营监控' in firstPage
    #            print("Login User is Right!")
    #        except AssertionError as e:
    #            print('loginUser is Error')
    #            self.test_01_login()  # 非‘运营监控’则重新登录
    #    else:
    #        self.test_01_login()
    #    driver.find_element_by_id("com.dgcy.paysx:id/monitor_t").click()  # 点击运营监控
    #    WebDriverWait(driver, timewait).until(lambda x: x.find_element_by_id("com.dgcy.paysx:id/rb_all"))  # 等待显示所有数据
    #    print("正在每隔"+str(timewait)+"s循环获取到所有设备的状态.....")
    #    driver.find_element_by_id('com.dgcy.paysx:id/rb_all').click()  # 点击‘全部’
    #    while count == 0:
    #        driver.find_element_by_id('com.dgcy.paysx:id/rb_all').click()  # 点击‘全部’
    #        #print("等待了"+str(timewait)+"s,获取到所有设备的状态.....")
    #        time.sleep(timewait)
    def getsize(self):
        x = self.driver.get_window_size()['width']
        y = self.driver.get_window_size()['height']
        return (x, y)
    def test_04_DataReport(self,device="77250569",date="2018-1-28"):
        timewait=5
        datelist = date.split('-')
        #now=datetime.datetime.now().strftime('%Y-%m-%d')
        #nowlist=now.split('-')
        #yeardiff=int(nowlist[0])-int(datelist[0])
        #monthdiff=int(nowlist[1])-int(datelist[1])
        #daydiff=int(nowlist[2])-int(datelist[2])
        driver = self.driver
        assertelement = LotteryTests.isElementExist(self, "id=com.dgcy.paysx:id/more_t")#判断数据报表元素是否可见
        if assertelement:
            print("已登录在APP首页".decode("utf-8"))
        else:
            self.test_01_login()#如果不在APP首页则重新登录
        driver.find_element_by_id("com.dgcy.paysx:id/more_t").click()  # 点击数据报表
        WebDriverWait(driver, timewait).until(lambda x: x.find_element_by_id("com.dgcy.paysx:id/tickets_detail_group"))  # 等待数据报表页面可见
        driver.find_element_by_id('com.dgcy.paysx:id/tickets_detail_group').click()  # 点击所有设备下拉框
        WebDriverWait(driver, 5).until(lambda x: x.find_element_by_id("android:id/text1"))  # 等待显示下拉栏所有数据
        #cc=self.getsize()
        #print("手机屏幕大小为:".decode("utf-8")+str(cc))

        driver.find_element_by_android_uiautomator('new UiSelector().clickable(true).text("%s")'% device) .click()  # 点击下拉框所输入的设备
        print("选择的设备编号为:".decode("utf-8") + device)
        time.sleep(1)
        driver.find_element_by_id('com.dgcy.paysx:id/endTime_bt').click()  # 点击日期选择
        eleyear=driver.find_elements_by_id('android:id/numberpicker_input')[0]#当前年份元素
        beforeB=driver.find_elements_by_class_name('android.widget.Button')[0].size#获取上一格的尺寸
        currentyear=eleyear.text#获取当前默认年份
        #Ybounds=eleyear.size#获取年份的元素尺寸,年月日的高度都是一样的
        Ybounds0 = eleyear.location#获取年份的起始位置
        singlebounds = beforeB['height']  # 滑动一格的长度
        print("滑动的长度为:".decode("utf-8")+str(singlebounds))
        #print(Ybounds)
        print("起始坐标:".decode("utf-8")+str(Ybounds0))
        x1 = Ybounds0['x']  # 年份起始横坐标
        y1 = Ybounds0['y']  # 年份起始纵坐标
        yeardiff = int(currentyear) - int(datelist[0]) #当前年份和所选年份之差
        if str(yeardiff).count('-')==1 and str(yeardiff)[0] == '-':
            y2 = Ybounds0['y']-singlebounds#如果年份之差为负数则向上滑动
            swipecount=int(str(yeardiff)[1])
        else:
            y2 = singlebounds + Ybounds0['y']  #如果年份之差为负数则向下滑动
            swipecount = yeardiff
        if swipecount > 0:
            for i in range(0,swipecount):
                eleyear.click()
                driver.swipe(x1, y1, x1, y2)  # 年份滑动一格
                if eleyear.text == str(int(datelist[0])) :
                    print("输入日期正确:".decode("utf-8")+eleyear.text+"".decode("utf-8"))
                    break
        else:
            print("输入日期正确:".decode("utf-8") + eleyear.text + "".decode("utf-8"))
        #print(eleyear.text)
        elemonth = driver.find_elements_by_id('android:id/numberpicker_input')[1]  # 当前月份元素
        currentmonth = elemonth.text  # 获取当前默认月份
        #Mbounds = elemonth.size  # 获取月份的元素尺寸,年月日的高度都是一样的
        Mbounds0 = elemonth.location  # 获取月份的起始位置
        x1 = Mbounds0['x']  # 月份起始横坐标
        y1 = Mbounds0['y']  # 月年份起始纵坐标
        monthdiff = int(currentmonth) - int(datelist[1])  # 当前月份和所选月份之差
        if str(monthdiff).count('-') == 1 and str(monthdiff)[0] == '-':
            y2 = Mbounds0['y'] - singlebounds  # 如果月份之差为负数则向上滑动
            swipecount = int(str(monthdiff)[1])
        else:
            y2 = singlebounds + Mbounds0['y']  # 如果月份之差为负数则向下滑动
            swipecount = monthdiff
        if swipecount>0:
            for i in range(0,swipecount):
                elemonth.click()
                driver.swipe(x1, y1, x1, y2)  # 月份滑动一格
                if elemonth.text == str(int(datelist[1])) :
                    print("输入日期正确:".decode("utf-8") + elemonth.text+"".decode("utf-8"))
                    break
        else:
            print("输入日期正确:".decode("utf-8") + elemonth.text + "".decode("utf-8"))
        #print(elemonth.text)
        eleday = driver.find_elements_by_id('android:id/numberpicker_input')[2]  # 当前日元素
        currentday = eleday.text  # 获取当前默认日
        #Dbounds = eleday.size  # 获取日的元素尺寸,年月日的高度都是一样的
        Dbounds0 = eleday.location  # 获取日的起始位置
        x1 = Dbounds0['x']  # 日起始横坐标
        y1 = Dbounds0['y']  # 日份起始纵坐标
        daydiff = int(currentday) - int(datelist[2])  # 当前日和所选日之差
        if str(daydiff).count('-') == 1 and str(daydiff)[0] == '-':
            y2 = Dbounds0['y'] - singlebounds  # 如果日之差为负数则向上滑动
            swipecount = int(str(daydiff)[1])
        else:
            y2 = singlebounds + Dbounds0['y']  # 如果日之差为负数则向下滑动
            swipecount = daydiff
        if swipecount > 0:
            for i in range(0,swipecount):
                eleday.click()
                driver.swipe(x1, y1, x1, y2)  # 日滑动一格
                if str(eleday.text) == str(datelist[2]) :
                    print("输入日期正确:".decode("utf-8") + eleday.text+"".decode("utf-8"))
                    break
        else:
            print("输入日期正确:".decode("utf-8") + eleday.text + "".decode("utf-8"))
        #print(eleday.text)
        driver.find_element_by_id('com.dgcy.paysx:id/date_picker_ok').click()#点击确定
        driver.find_element_by_id('com.dgcy.paysx:id/search_adv').click()  # 点击查询
        #elm = driver.find_elements_by_id('android:id/text1')  # 获取下拉所有元素
        #driver.find_elements_by_id("android:id/text1")[0].click()#点击下拉框第一个元素
        #print elm
        #num=len(elm)
        #print(num)
        #num=num-1
        #for i in range(num):
        #       driver.find_element_by_id("com.dgcy.paysx:id/tickets_detail_group").click()#点击设备下拉按钮
        #       time.sleep(1)
        #       driver.find_elements_by_id('android:id/text1')[i].click()#在下拉选择框选择设备并点击
        #       deviceNO=driver.find_elements_by_id('android:id/text1')[i].text()#获取设备编号
        #       print("选择的设备编号为:".decode("utf-8")+deviceNO)
        #       time.sleep(1)
        #       driver.find_element_by_id('com.dgcy.paysx:id/endTime_bt').click()#点击日期选择
        #       print("点击并选择日期".decode("utf-8"))
        #       time.sleep(1)
        time.sleep(10)
    def tearDown(self):
       self.driver.quit()

if __name__ == '__main__':
    #构造测试套件
    suite = unittest.TestSuite(tests=[LotteryTests('test_04_DataReport')])
View Code

 

完毕,如果哪位有更好的办法,欢迎指教!

 

转载于:https://www.cnblogs.com/lkc-test/p/10314110.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值