Esempio n. 1
0
    def test(self):
        DeviceNum = 'APU0215B25001477'
        device = Android(DeviceNum)
        poco = AndroidUiautomationPoco(device)

        poco.swipe([0.4, 0.8], [0.4, 0.5], duration=0.3)
        pass
Esempio n. 2
0
def vivo():
    # device_1 = connect_device('android://192.168.103.156:48887/339b19f1?cap_method=javacap&touch_method=adb')
    # device_1 = connect_device('android:///192.168.103.156:48887?cap_method=javacap&touch_method=adb')
    device_1 = connect_device(
        'android:///192.168.0.106:48887?cap_method=javacap&touch_method=adb')
    # device_1 = Android('android://192.168.103.156:48887?cap_method=javacap&touch_method=adb')
    poco = AndroidUiautomationPoco(device=device_1,
                                   use_airtest_input=True,
                                   screenshot_each_action=False)
    # poco(text="今日头条极速版").click()
    # poco(name="com.ss.android.article.lite:id/adg").click()
    # poco(name="com.ss.android.article.lite:id/qp").set_text("古剑奇谭三")
    for i in range(500):
        print(i)
        time.sleep(1)
        poco.swipe([0.5, 0.8], [0.5, 0.2])
Esempio n. 3
0
 def switchRatioAndSavePhoto(self):
     poco = AndroidUiautomationPoco( use_airtest_input=True, screenshot_each_action=False )
     sleep( 5 )
     poco( text="图片标记" ).click()
     poco.swipe( [0.5, 0.7], [0.5, 0.3] )
     sleep( 5 )
     poco.click( [0.4, 0.4] )
     poco( text="制作" ).click()
     sleep(2)
     poco( text="编辑" ).click()
     sleep(2)
     poco( text="3:4" ).click()
     poco( text="完成" ).click()
     sleep(2)
     poco( text="保存" ).click()
     sleep(2)
     poco( text="返回首页").click()
Esempio n. 4
0
class Testapp(unittest.TestCase):
    def setUp(self) -> None:
        self.poco = AndroidUiautomationPoco(use_airtest_input=True,
                                            screenshot_each_action=False)
        if not cli_setup():
            auto_setup(app_path,
                       devices=["Android://127.0.0.1:5037/emulator-5554"],
                       logdir=applog_path)
        start_app('com.tencent.mtt.x86')
        ST.SNAPSHOT_QUALITY = 75  # 设置全局的截图压缩精度
        if G.DEVICE.display_info['orientation'] in [1, 3]:
            '''判断当前手机是横屏还是竖屏,并获取当前分辨率,相对坐标=绝对坐标/width or height'''
            '''touch使用绝对坐标,poco使用相对坐标'''
            self.height = G.DEVICE.display_info['wigth']
            self.width = G.DEVICE.display_info['height']
        else:
            self.height = G.DEVICE.display_info['height']
            self.width = G.DEVICE.display_info['width']
        self.screen = G.DEVICE.snapshot()  #调用举报截图函数

    @unittest.skip('app用例单独测试')
    def test_app(self):
        self.poco(name='android.view.View').wait_for_appearance()
        self.poco(name='android.view.View').click()
        self.poco(text="搜索或输入网址").click()
        text("测试", enter=False)
        screen = aircv.crop_image(self.screen, (27, 98, 902, 197))
        self.poco.swipe([0.5, 0.5], [0.1, 0.1])
        # try_log_screen(screen) #报错局部截图到log文件中
        # 生成测试报告
        dev = device()
        dev.swipe_along([[959, 418], [1157, 564], [1044, 824], [751, 638],
                         [945, 415]])
        '''长距离多点滑动'''
        dev.pinch(in_or_out='in', center=None, percent=0.5)
        '''双指向内捏合动作,向外的话in改成out'''
        from airtest.report.report import simple_report
        simple_report(__file__,
                      logpath=applog_path,
                      output=(os.path.join(report_path, '%s.html') %
                              (time.strftime('%Y-%m-%d-%H-%M-%S'))
                              ))  #用airtest的方法生成报告,徐填写log.txt的位置,以及输出报告的位置

    def tearDown(self) -> None:
        stop_app('com.tencent.mtt.x86')
        '''每次结束后关闭APP'''
Esempio n. 5
0
def taskA(x,y):
    device_vivo = connect_device('android:339b19f1')  # vivo
    poco_vivo = AndroidUiautomationPoco(device=device_vivo, use_airtest_input=True, screenshot_each_action=False)
    device_huawei = connect_device('android:T7G0215804000411')
    poco_huawei = AndroidUiautomationPoco(device=device_huawei, use_airtest_input=True, screenshot_each_action=False)

    for i in range(1):
        #     poco1.swipe([0.5, 0.8], [0.5, 0.2])
        # 首页
        poco_vivo("android.widget.LinearLayout").offspring("android:id/tabs").child("android.widget.RelativeLayout")[
            0].child("com.ss.android.article.lite:id/axy").click()
        poco_vivo("android.widget.LinearLayout").offspring("android:id/tabs").child("android.widget.RelativeLayout")[
            0].child("com.ss.android.article.lite:id/axy").click()
        time.sleep(10)
        poco_vivo.swipe([0.5, 0.8], [0.5, 0.2])
        time.sleep(10)
        # 视频
        poco_vivo("android.widget.LinearLayout").offspring("android:id/tabs").child("android.widget.RelativeLayout")[
            1].child("com.ss.android.article.lite:id/axy").click()
        poco_vivo("android.widget.LinearLayout").offspring("android:id/tabs").child("android.widget.RelativeLayout")[
            1].child("com.ss.android.article.lite:id/axy").click()
        time.sleep(10)
        poco_vivo.swipe([0.5, 0.8], [0.5, 0.2])
        time.sleep(10)
        # 评论
        poco_vivo("com.ss.android.article.lite:id/ank").click()
        time.sleep(20)
        # 返回
        poco_vivo("com.ss.android.article.lite:id/aid").click()

            # 首页
        poco_huawei("android.widget.LinearLayout").offspring("android:id/tabs").child("android.widget.RelativeLayout")[
            0].child("com.ss.android.article.lite:id/axy").click()
        poco_huawei("android.widget.LinearLayout").offspring("android:id/tabs").child("android.widget.RelativeLayout")[
            0].child("com.ss.android.article.lite:id/axy").click()
        time.sleep(10)
        poco_huawei.swipe([0.5, 0.8], [0.5, 0.2])
        time.sleep(10)
        # 视频
        poco_huawei("android.widget.LinearLayout").offspring("android:id/tabs").child("android.widget.RelativeLayout")[
            1].child("com.ss.android.article.lite:id/axy").click()
        poco_huawei("android.widget.LinearLayout").offspring("android:id/tabs").child("android.widget.RelativeLayout")[
            1].child("com.ss.android.article.lite:id/axy").click()
        time.sleep(10)
        poco_huawei.swipe([0.5, 0.8], [0.5, 0.2])
        time.sleep(10)
        # 评论
        poco_huawei("com.ss.android.article.lite:id/ank").click()
        time.sleep(20)
        # 返回
        poco_huawei("com.ss.android.article.lite:id/aid").click()
    return x + y
Esempio n. 6
0
from airtest.core.api import *
from poco.drivers.android.uiautomation import AndroidUiautomationPoco

auto_setup(__file__)
dev1 = connect_device(
    'Android:///127.0.0.1:62001?cap_method=JAVACAP&&ori_method=ADBORI&&touch_method=ADBTOUCH'
)
poco = AndroidUiautomationPoco(dev1,
                               use_airtest_input=True,
                               screenshot_each_action=False)
clear_app('com.yozo.office')
start_app('com.yozo.office')
while True:
    sleep(0.5)
    while poco(text="允许").exists():
        poco(text="允许").click()
    sleep(0.5)
    while poco(text="始终允许").exists():
        poco(text="始终允许").click()
    sleep(0.5)
    if poco("com.yozo.office:id/rl_1").exists():
        break
while not poco("com.yozo.office:id/ll_usednow").exists():
    poco.swipe([0.8, 0.5], [0, 0.5])
poco("com.yozo.office:id/ll_usednow").wait().click()
            continue
        if result.offspring("com.jqorz.szk:id/lv_OpinionA"):
            dict['A'] = result.offspring("com.jqorz.szk:id/lv_OpinionA").child(
                name='com.jqorz.szk:id/tv_OpinionA_Content').get_text()
        if result.offspring("com.jqorz.szk:id/lv_OpinionB"):
            dict['B'] = result.offspring("com.jqorz.szk:id/lv_OpinionB").child(
                name='com.jqorz.szk:id/tv_OpinionB_Content').get_text()
        if result.offspring("com.jqorz.szk:id/lv_OpinionC"):
            dict['C'] = result.offspring("com.jqorz.szk:id/lv_OpinionC").child(
                name='com.jqorz.szk:id/tv_OpinionC_Content').get_text()
        if result.offspring("com.jqorz.szk:id/lv_OpinionD"):
            dict['D'] = result.offspring("com.jqorz.szk:id/lv_OpinionD").child(
                name='com.jqorz.szk:id/tv_OpinionD_Content').get_text()
        #检查答案是否存在,不存在就跳过
        if result.offspring("com.jqorz.szk:id/tv_Answer_Content"):
            answer = result.offspring(
                "com.jqorz.szk:id/tv_Answer_Content").get_text()
            dict['answer'] = answer
        else:
            continue
        print(serial, dict)
        #存储入总词典
        all_questions[serial] = dict
    if dict == dict2 and dict != {}:
        print(dict, dict2)
        break
    dict2 = dict
    poco.swipe([0.5, 0.8], [0.5, 0.2])

print(all_questions)
Esempio n. 8
0
poco_2 = AndroidUiautomationPoco(device_2,
                                 use_airtest_input=True,
                                 screenshot_each_action=False)

# poco_1(name="com.ss.android.ugc.aweme:id/bjc").wait_for_appearance()
# poco_1(name="com.ss.android.ugc.aweme:id/bjc").wait(10).exists()

poco_1(text="知乎").click()
sleep(15)

poco_1(name="com.zhihu.android:id/input").click()
sleep(1)
poco_1(name="com.zhihu.android:id/input").set_text("python")

res_list = poco_1("com.zhihu.android:id/parent_fragment_content_id").offspring(
    "android.support.v7.widget.RecyclerView").child(
        "android.widget.LinearLayout")
sleep(5)

for res in res_list:
    title = res.child(name="com.zhihu.android:id/magi_title").get_text()
    count = res.child(name="com.zhihu.android:id/magi_count").get_text()
    print(title, count)

poco_1(name="com.zhihu.android:id/magi_title")[0].click()
sleep(2)
while True:
    poco_1.swipe([0.5, 0.9], [0.5, 0.1], duration=0.1)
    title_objs = poco_1(name="com.zhihu.android:id/body_title")
    for title_obj in title_objs:
        print(title_obj.get_text())
Esempio n. 9
0
class AirtestPoco(object):
    """
    Airtest和Poco的方法集合
    airtest-api
        self.api,methods
    poco-Selector
        text, textMatches
    """
    def __init__(self, device):
        """
        init初始化
        """
        # 设置日志目录
        set_logdir(AIRTEST_LOG)
        # 删除旧日志
        clear_log(ST.LOG_DIR)
        # 初始化日志
        init_logging()
        # 等待显示时间
        self.timeout = ST.FIND_TIMEOUT

        # airtest-api
        self.api = api
        self.poco = AndroidUiautomationPoco(device,
                                            use_airtest_input=True,
                                            screenshot_each_action=False)
        self.UIObj = UIObjectProxy(poco=self.poco)

    """
    AirTest-Method
    封装的都是跟图片相关的
    """

    @classmethod
    def temp(cls,
             img_name: str,
             rgb: bool = True,
             record_pos: tuple = (0.5, -0.5),
             resolution: tuple = airDev.screen,
             target_pos=TargetPos.MID):
        """CV识别主函数
        :param rgb: 灰度识别还是色彩识别
        :param record_pos: 图片坐标
        :param img_name: 图片名称
        :param target_pos:
        :param resolution: 设备分辨率
        :return:
        """
        temp = Template(r"%s" % img_name,
                        target_pos=target_pos,
                        record_pos=record_pos,
                        resolution=resolution,
                        rgb=rgb)
        return temp

    @allure.step("元素点击:")
    def touch(self, v: Template, **kwargs):
        """
        在设备屏幕上执行触摸操作
        :param v: 要触摸的目标,可以是Template实例,也可以是绝对坐标(x,y)
        :param kwargs: [times  要执行多少次触摸]
        """
        self.api.touch(v, **kwargs)

    @allure.step("输入文本:")
    def text(self, text, enter=True, **kwargs):
        """
        目标设备上的输入文本。文本输入部件必须首先是活动的。
        :param text: 输入文本,支持unicode
        :param enter:输入' enter '键事件后文本输入,默认为真
        :param kwargs:
        :return:
        :platforms: Android, Windows, iOS
        """
        self.api.text(text, enter=enter, **kwargs)
        self.api.sleep()

    @allure.step("双击元素:")
    def double_click(self, v: Template):
        """双击"""
        self.api.double_click(v)

    @allure.step("滑动元素:")
    def swipe(self, v1, v2=None, vector=None, **kwargs):
        """
        在设备屏幕上执行滑动操作。
        分配参数有两种方法
            swipe(v1, v2=Template(...)) #从v1滑动到v2
            swipe(v1, vector=(x, y)) #滑动从v1开始并沿向量移动。
        :param:v1 –滑动的起点,可以是Template实例,也可以是绝对坐标(x,y)
        :param:v2 –滑动的终点,可以是Template实例,也可以是绝对坐标(x,y)
        :param:vector - 向量 –滑动动作的向量坐标,可以是绝对坐标(x,y)或屏幕百分比,例如(0.5,0.5)
        :param:**kwargs – 平台特定的kwargs,请参考相应的文档
        :exception: 异常 –如果提供的参数不足以执行交换操作,则为一般异常
        平台:	Android,Windows,iOS
        :return: 原点位置和目标位置
        """
        if v1.endswith('.png'):
            v1 = self.temp(v1)
        if v2.endswith('.png'):
            v2 = self.temp(v2)
        return self.api.swipe(v1, v2, vector, **kwargs)

    @allure.step("等待元素:")
    def wait(self, v: Template, **kwargs):
        """
        等待与设备屏幕上的模板匹配
        :param v –等待的目标对象,模板实例
        :param 超时 –等待比赛的时间间隔,默认为无,即ST.FIND_TIMEOUT
        :param interval –尝试找到匹配项的时间间隔(以秒为单位)
        :param intervalfunc –在每次未成功尝试找到相应匹配项后调用
        """
        self.api.wait(v, **kwargs)

    @allure.step("元素存在:")
    def exists(self, v: Template):
        """
        检查设备屏幕上是否存在给定目标
        :param v –检查对象
        :return 如果找不到目标,则为False,否则返回目标的坐标
        """
        return self.api.exists(v)

    @allure.step("断言目标存在:")
    def assert_exists(self, v: Template, msg: str = None):
        """
        断言目标存在于设备屏幕上
        :param v –要检查的目标
        :param msg –断言的简短描述,它将记录在报告中
        """
        self.api.assert_exists(v, msg)

    @allure.step("断言目标不存在:")
    def assert_not_exists(self, v: Template, msg: str = None):
        """
        断言目标在设备屏幕上不存在
        :param v –要检查的目标
        :param msg –断言的简短描述,它将记录在报告中
        """
        self.api.assert_not_exists(v, msg)

    @allure.step("查找所有匹配的:")
    def find_all(self, v: Template):
        """
        在设备屏幕上查找目标的所有位置并返回其坐标
        :param v:要查找的目标
        :return:坐标列表,[(x,y),(x1,y1),…]
        :平台:Android、Windows、iOS
        """
        return self.api.find_all(v)

    def capture_screenshot(self, bs64=True):
        """
        截图保存为base64
        :return:
        """
        filename = self.api.snapshot()['screen']
        filepath = os.path.join(ST.LOG_DIR, filename)
        allure.attach.file(filepath, "截图" + filename,
                           allure.attachment_type.JPG)
        if bs64:
            with open(filepath, 'rb') as f:
                imagebase64 = base64.b64encode(f.read())
            return imagebase64.decode()

    """
    poco-method
    """

    @allure.step("poco等待一个元素显示:")
    def poco_wait_any(self, objects: list):
        """
        等待,直到所有给定的一个 UI 代理在超时之前显示。将定期轮询所有 UI 代理。
        :param objects:
        :return: bool
        """
        try:
            return self.poco.wait_for_any(objects, timeout=self.timeout)
        except poco_exception.PocoTargetTimeout:
            return False

    @allure.step("poco等待多个元素显示:")
    def poco_wait_all(self, objects: list):
        """
        等待,直到所有给定的所有 UI 代理在超时之前显示。将定期轮询所有 UI 代理。
        :param objects:
        :return:
        """
        try:
            self.poco.wait_for_all(objects, timeout=self.timeout)
            return True
        except poco_exception.PocoTargetTimeout:
            return False

    def poco_obj(self, **kwargs):
        """poco实例"""
        if 'index' in kwargs:
            index = kwargs.pop('index')
            ele = self.poco(**kwargs)[index]
        else:
            ele = self.poco(**kwargs)
        ele.wait_for_appearance(timeout=self.timeout)
        return ele

    @allure.step("poco点击元素:")
    def poco_click(self, **kwargs):
        """
        对由UI代理表示的UI元素执行click操作。如果这个UI代理代表一组
        UI元素,单击集合中的第一个元素,并将UI元素的定位点用作默认值
        一个。还可以通过提供“focus”参数单击另一个点偏移。
        :param kwargs: [text, name]
        """
        log("点击元素:{}".format(kwargs))
        self.poco_obj(**kwargs).click()
        self.poco.sleep_for_polling_interval()

    @allure.step("poco点击pos:")
    def poco_click_pos(self, pos):
        """
        在给定坐标下对目标设备执行单击(触摸,轻击等)操作。坐标(x, y)是一个2-列表或2-元组。
        x和y的坐标值必须在0 ~ 1之间,以表示屏幕的百分比。
        例如:
            坐标[0.5,0.5]表示屏幕的中心,坐标[0,0]表示左上角。
            有关坐标系统的详细信息,请参阅CoordinateSystem。
        实际案例:
            单击分辨率为(1920,1080)的屏幕的(100,100)点:
                poco.click([100.0 / 1920, 100.0 / 1080])
        :param pos: (list(float, float) / tuple(float, float)) – coordinates (x, y) in range of 0 to 1
        :return:
        """
        self.poco.click(pos)
        self.poco.sleep_for_polling_interval()

    @allure.step("poco获取元素文本:")
    def poco_text(self, **kwargs):
        """
        获取 UI 元素的文本属性。如果没有此类属性,则返回"无"。
        :param kwargs:
        :return: txt
        """
        txt = self.poco_obj(**kwargs).get_text()
        log("获取元素{}文本:{}".format(kwargs, txt))
        return txt

    @allure.step("poco获取元素属性:")
    def poco_attr(self, name, **kwargs):
        """
        按给定属性名称检索 UI 元素的属性。如果属性不存在,则返回"无"。
            visible:用户是否可见
            text:UI 元素的字符串值
            type:远程运行时的 UI 元素的类型名称
            pos:UI 元素的位置
            size:根据屏幕,0+1 范围内的百分比大小 [宽度、高度]
            name:UI 元素的名称
            ...: other sdk 实现的属性
        :return:
        """
        return self.poco_obj(**kwargs).attr(name)

    def poco_freeze(self, **kwargs):
        """冻结UI树并返回当前的UI结果树"""
        with self.poco.freeze() as freeze:
            return freeze(**kwargs)

    def poco_hierarchy_dict(self):
        """获取当前结构树的字典"""
        frozen_poco = self.poco.freeze()
        hierarchy_dict = frozen_poco.agent.hierarchy.dump()
        return hierarchy_dict

    @allure.step("poco元素存在:")
    def poco_exists(self, **kwargs):
        """
        测试UI元素是否在层次结构中
        :param kwargs: [text,name]
        """
        result = self.poco_freeze(**kwargs).exists()
        log("元素{}验证结果: {}".format(kwargs, result))
        return result

    @allure.step("poco滚动屏幕:")
    def poco_scroll(self,
                    direction: str = 'vertical',
                    percent: float = 0.5,
                    duration: float = 2.0):
        """
        从整个屏幕的下部滚动到上部
        默认的 direction='vertical', percent=0.6, duration=2.0
        :param direction: 方向:滚动方向。垂直(vertical)或“水平”(horizontal)
        :param duration: 百分比:根据
        :param percent: 持续时间:执行操作的时间间隔
        """
        self.poco.scroll(direction=direction,
                         percent=percent,
                         duration=duration)

    @allure.step("poco滑动:")
    def poco_swipe(self, p1, p2=None, direction=None, duration: float = 2.0):
        """
        在目标设备上通过起点和终点或方向向量指定的点到点执行滑动操作。必须至少提供端点或方向之一。
        点的坐标(x,y)定义与click事件的定义相同。方向矢量(x,y)的分量也以0到1的屏幕范围表示。
        请参阅CoordinateSystem以获取有关坐标系的更多详细信息。
        实际案例
            以下示例显示了如何在分辨率为1920x1080的屏幕上执行从(100,100)到(100,200)的滑动动作:
                poco.swipe([100.0 / 1920, 100.0 / 1080], [100.0 / 1920, 200.0 / 1080])
            或由特定方向而非终点给定:
                poco.swipe([100.0 / 1920, 100.0 / 1080], direction=[0, 100.0 / 1080])
        :param p1: 起点
        :param p2: 终点
        :param direction: 滑动方向
        :param duration: 持续时间(float)–执行滑动操作的时间间隔
        """
        self.poco.swipe(p1=p1, p2=p2, direction=direction, duration=duration)

    """
    aircv-method
    """

    @allure.step("元素截图:")
    def crop_image(self, rect: list):
        """局部截图
        :param rect = [x_min, y_min, x_max ,y_max].
        :return filepath 图片路径
        """
        # 局部截图
        img = G.DEVICE.snapshot()
        crop_screen = crop_image(img, rect)
        # 生成截图路径
        filename = "%(time)d.jpg" % {'time': timestamp() * 1000}
        filepath = os.path.join(ST.LOG_DIR, filename)
        # 保存局部截图到logs文件夹中
        pil_image = cv2_2_pil(crop_screen)
        pil_image.save(filepath, quality=99, optimize=True)
        return filepath

    @allure.step("图片文字识别:")
    def tesseract_string(self, filepath, lang='eng+chi_sim', config='--psm 6'):
        """识别图片文字"""
        # 读取图片
        im = Image.open(filepath)
        # 识别图片文字
        # 进行置灰处理
        im = im.convert('L')
        # 这个是二值化阈值
        threshold = 150
        table = []
        for i in range(256):
            if i < threshold:
                table.append(0)
            else:
                table.append(1)
        # 通过表格转换成二进制图片,1的作用是白色,0就是黑色
        im = im.point(table, "1")
        result = pytesseract.image_to_string(im, lang=lang, config=config)
        # 返回并清除结果的空格
        return result.replace(" ", "")
Esempio n. 10
0
    def huawei(self):
        try:
            device_2 = connect_device('android:T7G0215804000411')
            poco = AndroidUiautomationPoco(device=device_2, use_airtest_input=True, screenshot_each_action=False)
            # poco = AndroidUiautomationPoco(use_airtest_input=True, screenshot_each_action=False)

            for i in range(1,1000):
                print(f'第{i}次滑动!')
                poco.swipe([0.5, 0.8], [0.5, 0.2])
                time.sleep(self.wait_time)
                # 判断说是不是广告
                try:
                    #a7l
                    wenan = poco(name="com.ss.android.ugc.aweme:id/a7l").get_text()
                    if '[t]' in wenan:
                        print('this is a ad!')
                        continue
                    # ad_text = poco(name="com.ss.android.ugc.aweme:id/buf").get_text()
                    # print(f'ad_text:{ad_text}')
                    # if '查看详情' in ad_text:
                    #     print('this is a ad!')
                    #     continue
                except:
                    print('this not is a ad!')
                # with open('ad.txt','w') as f:
                #     f.write(ad_text)
                # 点击进入个人中心
                # 获取主播昵称
                text = poco(name="com.ss.android.ugc.aweme:id/title").get_text()
                self.write_file('users_name.txt',text)
                poco(name="com.ss.android.ugc.aweme:id/title").click()
                time.sleep(self.wait_time)

                # 进入商品橱窗
                try:
                    goods_text = poco(text="商品橱窗").get_text()
                    print(f'goods_text:{goods_text}')
                    if goods_text:
                        # poco(text="商品橱窗").click()
                        poco(name="com.ss.android.ugc.aweme:id/cl5").click()
                        # 返回
                        poco(name="com.ss.android.ugc.aweme:id/k4").click()
                except:
                    print('not hove goods!')
                # 返回
                try:
                    # poco(name="com.ss.android.ugc.aweme:id/kc").click()
                    poco(name="com.ss.android.ugc.aweme:id/k4").click()
                    time.sleep(self.wait_time)
                except:
                    # poco(name="com.ss.android.ugc.aweme:id/ww").click()
                    poco(name="com.ss.android.ugc.aweme:id/wf").click()
                    time.sleep(self.wait_time)

                # 点击进入音乐
                try:
                    # poco(name="com.ss.android.ugc.aweme:id/c3k").click()
                    poco(name="com.ss.android.ugc.aweme:id/c1o").click()
                    time.sleep(self.wait_time)
                    # poco(name="com.ss.android.ugc.aweme:id/kc").click()
                    poco(name="com.ss.android.ugc.aweme:id/k4").click()
                    time.sleep(self.wait_time)
                except:
                    #央视新闻
                    print('this music is not useful!')
            return True
            # 获取视频页面内容
            # text = poco(name="com.ss.android.ugc.aweme:id/a87").get_text()
            # self.write_file('users_name.txt',text)
        except:
            return False
Esempio n. 11
0
def main(DeviceNum):
    # 多设备连接时,可指定设备编号
    # python -m airtest run main.py --device Android://127.0.0.1:5037/0123456789ABCDEF
    # device = Android('GWY0216C16002906')
    # 设备类型 1 手机[720,1280][1080,1920] 2平板[1200,1920]
    # DeviceNum = 'c5bac654'
    NeedSwipe = ['CLB0218414001154', 'DLQ0216824000142', 'E4J4C17405011422',
                 'APU0216530000778', 'APU0216408028484', 'APU0216111008105']
    try:
        DbContext = DbHelper()
        DeviceType = 0
        device = Android(DeviceNum)
        # device.adb.start_shell("su")
        # device.adb.start_shell("wipe data")
        # device.adb.start_shell("wipe cache")
        # device.adb.start_cmd("adb reboot")

        if '0123456789ABCDEF' not in DeviceNum:
            device.wake()  # 唤醒页面
            poco = AndroidUiautomationPoco(device)
            # if DeviceNum in NeedSwipe:
            poco.swipe([0.4, 0.9], [0.4, 0.55], duration=0.1)
            time.sleep(2)
            # 复位一下,防止之前没有睡眠也滑动
            poco.swipe([0.4, 0.45], [0.4, 0.9], duration=0.1)
        else:
            poco = AndroidUiautomationPoco(
                use_airtest_input=True, screenshot_each_action=False)
        # ClearMemory(device,poco,'')
        # return
        device_screen = poco.get_screen_size()
        device_x = device_screen[0]
        device_y = device_screen[1]
        print(str(device_y), str(device_x))
        if device_y > 1600 and device_x > 1080:
            DeviceType = 2
        else:
            DeviceType = 1
        if DeviceType == 0:
            print(
                '\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~o(╥﹏╥)o 设备型号无法确定 o(╥﹏╥)o~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~')
            DbContext.AddLog(DeviceNum, 3, '设备[' + DeviceNum + ']型号无法确定')
            return
        elif DeviceType == 1:
            print(
                '\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~O(∩_∩)O 设备型号为手机 O(∩_∩)O~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n')
        else:
            print(
                '\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~O(∩_∩)O 设备型号为平板 O(∩_∩)O~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n')
    except Exception as e:
        print('\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~o(╥﹏╥)o 设备连接异常 o(╥﹏╥)o~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~')
        DbContext.AddLog(
            DeviceNum, 3, "设备[" + DeviceNum + "]连接异常:" + repr(e).replace("'", ""))
    else:
        BackHomeStatus = BackHomePage(
            poco, DbContext, DeviceNum, device)  # 返回首页
        if BackHomeStatus:
            mode = DbContext.GetDeviceRunningMode(DeviceNum)
            taskList = []
            # 获取当前设备要抓取的城市
            IsRunning = True
            if mode == 1:
                taskList = DbContext.GetDeviceTask(DeviceNum)
            elif mode == 2:
                taskList = DbContext.GetDeviceTaskByMode2()
            elif mode == 3:
                taskList = DbContext.GetDeviceTaskByMode3()
            elif mode == 5:
                IsRunning = False
            elif mode == 6:
                # 根据店名爬取
                while True:
                    data = get_shopName()
                    id_name_addr_city = data[0]
                    shopid = id_name_addr_city[0]
                    storeName = id_name_addr_city[1]
                    addr = id_name_addr_city[2]
                    city = (id_name_addr_city[3])[:-1]
                    print(storeName, addr, city)
                    if data[1] == 3:
                        crawl_status_code(storeName, 3)
                    else:
                        crawl_status_code(storeName, 1)
                    search_store(storeName, poco, device, addr, city, shopid)
                    BackHomePage(poco, DbContext, DeviceNum, device)
                    crawl_status_code(storeName, 2)

            if(len(taskList) == 1):
                # 更新任务为运行中
                DbContext.UpdateTaskStatus(
                    int(taskList[0]['TaskId']), 1, 0, mode)
            while IsRunning:
                BackHomeStatus = BackHomePage(
                    poco, DbContext, DeviceNum, device)  # 返回首页
                if BackHomeStatus:
                    for task in taskList:
                        # AddressList(task['TargetCity']) #获取未抓取的坐标点
                        AllPosition = [
                            {'RepresentativeAdress': task['RepresentativeAdress'], 'Genhash':task['Genhash']}]
                        taskId = task['TaskId']
                        cityCode = task['CityCode']
                        # 更新任务为运行中
                        DbContext.UpdateTaskStatus(int(taskId), 1, 0, mode)
                        # 计时
                        StartTime = datetime.datetime.now()
                        # 返回值需要写进队列
                        currentTaskResult, IsEmergencyStop = StartCapture(
                            poco, AllPosition, DeviceType, task['TargetCity'], DeviceNum, cityCode, device)  # 抓取数据
                        # 没有紧急置停的情况下才完成后续的更新
                        if not IsEmergencyStop:
                            EndTime = datetime.datetime.now()
                            DbContext = DbHelper()
                            DbContext.AddLog(DeviceNum, 2, '设备[' + DeviceNum + ']本次抓取[' + AllPosition[0]['RepresentativeAdress'] + '] [' + str(
                                len(currentTaskResult)) + '] 家店,耗时:' + str(((EndTime - StartTime).seconds)/60))
                            # 更新任务为完成
                            DbContext.UpdateTaskStatus(
                                int(taskId), 2, len(currentTaskResult), mode)
                            # 将任务的执行结果回写到队列
                            if mode != 3:
                                Produce = SendMessage()
                                result = Produce.sendMessage(
                                    taskId, currentTaskResult)
                                if result:
                                    # 将任务状态改为已回写队列
                                    DbContext.UpdateTaskStatus(
                                        int(taskId), 3, len(currentTaskResult), mode)
                        else:
                            break
                    mode = DbContext.GetDeviceRunningMode(DeviceNum)
                    if len(taskList) > 0:
                        taskList.clear()
                    if mode == 1:
                        taskList = DbContext.GetDeviceTask(DeviceNum)
                    elif mode == 2:
                        taskList = DbContext.GetDeviceTaskByMode2()
                    elif mode == 3:
                        taskList = DbContext.GetDeviceTaskByMode3()
                    elif mode == 5:
                        print(
                            '~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~O(∩_∩)O 紧急置停 O(∩_∩)O~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~')
                        break
                    if len(taskList) > 0:
                        print(
                            '~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~O(∩_∩)O 抽取一条任务 O(∩_∩)O~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~')
                    else:
                        print(
                            '~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~O(∩_∩)O 任务执行完毕 O(∩_∩)O~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~')

                        break
                else:
                    DbContext.AddLog(
                        DeviceNum, 3, '设备[' + DeviceNum + ']返回首页异常')
                    break
        else:
            DbContext.AddLog(DeviceNum, 3, '设备[' + DeviceNum + ']返回首页异常')
# -*- encoding=utf8 -*-
__author__ = "chenwt"

from airtest.core.api import *

auto_setup(__file__)

from poco.drivers.android.uiautomation import AndroidUiautomationPoco
poco = AndroidUiautomationPoco(use_airtest_input=True,
                               screenshot_each_action=False)
poco(text="订单").click()
poco.swipe([0.5, 0.9359375], [0.5, 0.305525])
poco("com.iris.lshitaskse:id/tv_xiaosou_leixin").click()
#选择销售类型
poco(text="R1:正常零售").click()
#点击输入金额
poco("com.iris.lshitaskse:id/tv_input_jine").click()
#keyevent("Backspace")
text("15800")
poco("com.iris.lshitaskse:id/title").child(
    "android.widget.TextView")[1].click()
#输入意向金无息退款天数
poco("com.iris.lshitaskse:id/tv_input_tuikuan_tianshu").click()
text("1")
poco("com.iris.lshitaskse:id/title").child(
    "android.widget.TextView")[1].click()
#选择开票时间
poco("com.iris.lshitaskse:id/tv_input_yujikaipiaoriqi").click()
poco("com.iris.lshitaskse:id/btnSubmit").click()
poco("com.iris.lshitaskse:id/tv_tijiao").click()
poco("com.iris.lshitaskse:id/open").click()
Esempio n. 13
0
    def cardLogin2(self):
        # 调用公共方法
        ba = Base()
        try:
            poco = AndroidUiautomationPoco(use_airtest_input=True,
                                           screenshot_each_action=False)
            # 安装APP
            ba.install_app()
            sleep(10)
            # 启动APP
            ba.start_app()

            if not cli_setup():
                auto_setup(__file__, logdir="./case/cardLogin/log")
            sleep(2)
            print("----------------测试信用卡号登錄流程開始----------------------")
            sleep(10)

            # 点击快捷登录
            poco("android.widget.LinearLayout").offspring(
                "android.widget.FrameLayout").child(
                    "android.view.ViewGroup").child("android.view.ViewGroup")[
                        1].offspring("CreditCard, tab, 2 of 3").offspring(
                            "android.widget.ImageView").click()

            poco(text="快捷登錄").click()
            # 切换到信用卡号登录
            poco(text="證件號登錄").click()
            swipe(Template(r"tpl1576725488897.png",
                           record_pos=(0.006, 0.61),
                           resolution=(1080, 2280)),
                  vector=[0.1507, 0.0809])
            touch(
                Template(r"tpl1576725505334.png",
                         record_pos=(0.424, 0.455),
                         resolution=(1080, 2280)))

            # 输入卡号
            poco(text="請輸入信用卡卡號").click()
            poco(text="6").click()
            poco(text="2").click()
            poco(text="6").click()
            poco(text="2").click()
            poco(text="9").click()
            poco(text="5").click()
            poco(text="0").click()
            poco(text="0").click()
            poco(text="0").click()
            poco(text="0").click()
            poco(text="0").click()
            poco(text="0").click()
            poco(text="0").click()
            poco(text="1").click()
            poco(text="5").click()
            poco(text="4").click()

            # 输入查询密码
            poco(text="請輸入信用卡查詢密碼").click()
            poco(text="1").click()
            poco(text="2").click()
            poco(text="3").click()
            poco(text="4").click()
            poco(text="5").click()
            poco(text="6").click()
            # 点击下一步,进入短信接收页面
            poco(text="下一步").click()
            assert_exists(
                Template(r"tpl1576725845426.png",
                         record_pos=(0.001, -0.502),
                         resolution=(1080, 2280)), "发送短信成功")
            poco.swipe(point_a, center, direction)
            print("信用卡发送短信成功")
            print("----------------测试信用卡号流程結束----------------------")

            # 退出app
            ba.stop_app()

        except Exception as e:
            print("-------------异常情况-------------")
            ba.log_error("登陆流程错误: \n %s" % (e))
            print(e)
            # 退出app
            ba.stop_app()
Esempio n. 14
0
class WeVideo(object):

    def __init__(self):
        self.package_name = 'com.tencent.weishi'
        self.home_activity = 'com.tencent.oscar.module.splash.SplashActivity'

        # 配置日志
        LOG_FORMAT = "%(asctime)s - %(levelname)s - %(message)s"
        logging.basicConfig(filename='my.log', level=logging.DEBUG, format=LOG_FORMAT)

        # 互动红包元素【普通红包】
        self.image_red_package = './pic/red.png'

        # 互动红包元素【答题红包】
        self.image_red_package2 = './pic/red2.png'

        # 抢红包的切图元素【小红包】
        self.catch_red_package = './pic/red_catch.jpg'

        # 抢红包的切图元素【中红包】
        self.catch_red_package_more = './pic/red_catch_more.png'

        # 抢红包的切图元素【大红包】
        self.catch_red_package_most = './pic/red_catch_most.png'

        # 获得红包的元素
        self.get_red_package = './pic/part.jpg'

        self.wait_for_dialog_timeout = 10

        # 截图临时保存路径
        self.screenshot_pic_temp_path = './sc.jpg'

        self.poco = AndroidUiautomationPoco(screenshot_each_action=False)

        auto_setup(__file__)

    def __page_has_red_package(self):
        """
        当前视频是否包含红包
        :return:
        """
        # 截图当前页面
        save_screenshot_to_pc(self.screenshot_pic_temp_path)

        # 拿红包的截图去匹配
        result1 = find_image(self.screenshot_pic_temp_path, self.image_red_package)

        result2 = find_image(self.screenshot_pic_temp_path, self.image_red_package2)

        # 删除临时文件
        remove_cache(self.screenshot_pic_temp_path)

        # 不包含红包元素
        if result1:
            type_result = TypeRedPackage.Norm
            print("【普通红包】视频包含红包")
        elif result2:
            type_result = TypeRedPackage.MORE
            print("【答题红包】视频包含红包")
        else:
            type_result = TypeRedPackage.No
            print("【没有红包】下一条!!!")
            print('==' * 30)
        return type_result

    def run(self):
        # 打开应用
        self.__open_app()

        # 异步处理对话框
        threading.Thread(target=self.__handle_dialog, name='thread1').start()

        # 等待到达主页面
        self.poco('com.tencent.weishi:id/tv_home_tab_recommend', text=u'推荐').wait_for_appearance()

        print('到达首页')

        # 判断当前视频包含红包
        while True:
            print('==' * 30)
            print('开始新的一个视频')
            # 让视频缓存2s
            time.sleep(3)
            video_type = self.__page_has_red_package()
            if video_type == TypeRedPackage.Norm:
                # 抢普通红包
                self.__catch_red_package()
            elif video_type == TypeRedPackage.MORE:
                # 抢答题红包
                # 先答题
                self.__to_answer_question()

            # 滑动到下一个视频
            self.poco.swipe([0.5, 0.8], [0.5, 0.1], duration=0.2)

    def __open_app(self):
        """
        打开应用
        :return:
        """
        home()
        # stop_app(self.package_name)
        start_my_app(self.package_name, self.home_activity)

    def __handle_dialog(self):
        """
        处理警告对话框
        :return:
        """
        count = 0
        while count < self.wait_for_dialog_timeout:
            tip_notice = self.poco('com.tencent.weishi:id/title_text', text=u'青少年保护功能提示')
            try:
                if tip_notice.exists():
                    # 关闭
                    print('出现警告对话框,关闭之。')
                    self.poco('com.tencent.weishi:id/close_btn').click()
                    break
                else:
                    pass
            except Exception as e:
                print('产生异常了')

            time.sleep(1)
            count += 1

        # print('处理对话框时间到!!!')

    def __catch_red_package(self):
        """
        抢红包
        :return:
        """

        # 第一步:先找到红包的位置(有bug)
        # while True:
        #     # 截图匹配红包
        #     save_screenshot_to_pc(self.screenshot_pic_temp_path)
        #     # 匹配普通、大红包
        #     result1 = find_image(self.screenshot_pic_temp_path, self.catch_red_package)
        #     result2 = find_image(self.screenshot_pic_temp_path, self.catch_red_package_more)
        #     result3 = find_image(self.screenshot_pic_temp_path, self.catch_red_package_most)
        #     result = None
        #     if result1:
        #         result = result1
        #     elif result2:
        #         result = result2
        #     elif result3:
        #         result = result3
        #
        #     if result:
        #         print('找到红包!红包坐标如下:')
        #         print(result)
        #         break
        #     else:
        #         print('没有找到红包')

        while True:
            vp = self.poco('com.tencent.weishi:id/hippy_container')
            if vp.exists():
                # 元素
                try:
                    red_package_element = vp.children()[0].children()[0].children()[0].children()[0]
                except Exception:
                    print('产生一个异常')
                    continue

                # 获取bound()属性
                element_size = red_package_element.get_bounds()

                center_position = get_element_center_position(self.poco, element_size)

                # 一直等待红包元素出现,才执行点击操作
                if len(red_package_element.children()) > 0:
                    print(center_position)
                    break
                else:
                    # print('等待红包出现可以点击')
                    pass
            else:
                print('vp不存在')

        # 获取到红包坐标之后,执行点击点击操作,直到抢到红包为止
        exec_cmd('adb shell input tap %d %d' % (center_position[0], center_position[1]))

        time.sleep(3)

        # 红包元素图片匹配
        # while True:
        #     print('点击抢红包')
        #     # exec_cmd('adb shell input tap %d %d' % (result[0], result[0]))
        #     exec_cmd('adb shell input tap %d %d' % (center_position[0], center_position[1]))
        #     exec_cmd('adb shell input tap %d %d' % (center_position[0], center_position[1]))
        #     save_screenshot_to_pc(self.screenshot_pic_temp_path)
        #     result_get_red_package = find_image(self.screenshot_pic_temp_path, self.get_red_package)
        #
        #     if result_get_red_package:
        #         print('成功获取到红包')
        #         break
        #     else:
        #         print('没有获取红包,继续点击')

    def __getLastChild(self, vp):
        """
        遍历获取最后一级的Child
         # top, right, bottom, left
        :param vp:
        :return:
        """

        temp = vp
        while True:
            children_size = len(temp.children())
            if children_size == 0:
                break
            else:
                temp = temp.children()[0]
                print(temp.get_position())

        return temp
Esempio n. 15
0
                poco(text='保存视频').click()
                sleep(2)
                # 复制到PC端文件夹内
                copy_last_pic_to_local(WEI_XIN_FILE_PATH, adjunct_path)
                keyevent('BACK')

            moods.append(item)

    return True


# 6.1 获取首页可以见的动态
write_to_csv(True, None)

i = 0
while True:
    # 判断是否是24小时之内的内容
    if not get_dynamic_moods():
        break

    print('休眠5秒后继续滑动')
    sleep(5)

    print('第%d次滑动' % i)
    poco.swipe([0.5, 0.6], [0.5, 0.2], duration=0.5)
    i += 1

# 写入到csv文件中
write_to_csv(False, moods)

print('恭喜,爬取数据成功!')
Esempio n. 16
0
# -*- encoding=utf8 -*-
__author__ = "chenwt"

from airtest.core.api import *

from poco.drivers.android.uiautomation import AndroidUiautomationPoco
poco = AndroidUiautomationPoco(use_airtest_input=True, screenshot_each_action=False)


auto_setup(__file__)
poco(text="订单").click()
poco.swipe([0.5,0.8],[0.5,0.15])
poco("com.iris.dch.itask:id/tv_input_jine").click()
text("15700")
poco("com.iris.dch.itask:id/title").child("android.widget.TextView")[1].click()
poco("com.iris.dch.itask:id/tv_input_tuikuan_tianshu").click()
text("1")
poco("com.iris.dch.itask:id/title").child("android.widget.TextView")[1].click()
poco("com.iris.dch.itask:id/tv_input_yujikaipiaoriqi").click()
poco("com.iris.dch.itask:id/btnSubmit").click()
poco("com.iris.dch.itask:id/tv_tijiao").click()
poco("com.iris.dch.itask:id/open").click()
sleep(8)
#退出销售平台
poco("com.iris.dch.itask:id/title").child("android.widget.TextView")[0].click()
poco("com.iris.dch.itask:id/open").click()



Esempio n. 17
0
from airtest.core.api import *
from airtest.cli.parser import cli_setup

if not cli_setup():
    auto_setup(__file__, logdir=True, devices=[
            "Android://127.0.0.1:5037/6cb5fe5b",
    ])
print("start...")
from poco.drivers.android.uiautomation import AndroidUiautomationPoco
poco = AndroidUiautomationPoco(use_airtest_input=True, screenshot_each_action=False)
poco(text="捉妖记")
poco("android.widget.LinearLayout").offspring("android:id/content").offspring("com.sankuai.moviepro:id/root_recycle").child("android.widget.RelativeLayout")[2].child("com.sankuai.moviepro:id/first_layout")#poco("com.sankuai.moviepro:id/tv_information").click()
#poco(text="国产").click()
while True:
    poco.swipe([0.5,0.5],[0.5,0.623])
    #poco("com.sankuai.moviepro:id/mil_container").focus([0.5,0.5]).click()
    poco("com.sankuai.moviepro:id/root_recycle").focus([0.5,0.86]).click()
    mode = True
    k=1
    m=1
    while mode==True:
        sleep(1)
        snapshot(msg="当前界面.")
        poco.swipe([0.5,0.9],[0.5,0.1])
        k=k+1
        if k==5:
            touch(Template(r"tpl1558460717253.png", record_pos=(-0.454, -0.885), resolution=(1080, 2160)))
            mode =not mode
            break
            
Esempio n. 18
0
# -*- encoding=utf8 -*-
__author__ = "asus"

from airtest.core.api import *
from poco.drivers.android.uiautomation import AndroidUiautomationPoco
from airtest.cli.parser import cli_setup

if not cli_setup():
    auto_setup(
        __file__,
        logdir=True,
        devices=[
            "Android://127.0.0.1:5037/FKC4C16629002059?touch_method=ADBTOUCH",
        ])

# script contentpoco("android.widget.FrameLayout").child("android.widget.FrameLayout")
print("start...")
poco = AndroidUiautomationPoco(use_airtest_input=True,
                               screenshot_each_action=False)
keyevent('BACK')
poco.swipe([0.5, 0.7], [0.5, 0.3], duration=0.5)

# generate html report
# from airtest.report.report import simple_report
# simple_report(__file__, logpath=True)
Esempio n. 19
0
auto_setup(__file__)

touch(Template(r"tpl1590760159617.png", record_pos=(-0.115, -0.267), resolution=(1080, 2340)))

touch(Template(r"tpl1590761358552.png", record_pos=(-0.001, -0.376), resolution=(1080, 2340)))
poco.wait_for_all

time.sleep(3)
touch(Template(r"tpl1590761484189.png", record_pos=(-0.306, -0.939), resolution=(1080, 2340)))


# text("瓜分10亿")
text("618列车")
time.sleep(5)
poco.swipe([0.5,0.9],[0.5,0.4])
poco.swipe([0.5,0.9],[0.5,0.4])

poco.wait_for_all

ls = poco(name='android.view.View',touchable =  True)
print(len(ls))

if len(ls) > 0:

    for each in ls:
        if each.exists():
            each.click()
            poco.swipe([0.5,0.9],[0.5,0.2])
            time.sleep(17)
            poco.swipe([0.01,0.5],[0.6,0.5])
Esempio n. 20
0
             record_pos=(0.219, -0.736),
             resolution=(720, 1440)))
sleep(1.0)
sleep(1.0)
sleep(1.0)

touch(
    Template(r"tpl1605840322629.png",
             record_pos=(-0.003, -0.525),
             resolution=(720, 1440)))
sleep(1.0)
sleep(1.0)
sleep(1.0)
#swipe(Template(r"tpl1605841211820.png", record_pos=(0.003, 0.083), resolution=(720, 1440)), vector=[-0.3417, -0.05])

poco.swipe([930, 490], [268, 490], duration=2)

sleep(1.0)
sleep(1.0)

touch(
    Template(r"tpl1605841423666.png",
             record_pos=(0.386, 0.072),
             resolution=(720, 1440)))

sleep(1.0)
sleep(1.0)
sleep(1.0)
poco(text="提交").click()

touch(
Esempio n. 21
0
             record_pos=(-0.115, -0.267),
             resolution=(1080, 2340)))

touch(
    Template(r"tpl1590760188586.png",
             record_pos=(0.246, -0.374),
             resolution=(1080, 2340)))

time.sleep(6)

touch(
    Template(r"tpl1590760253235.png",
             record_pos=(0.406, 0.48),
             resolution=(1080, 2340)))
time.sleep(3)
poco.swipe([0.5, 0.9], [0.5, 0.7])

for i in range(5):

    poco.swipe([0.5, 0.8], [0.5, 0.5])

    touch(
        Template(r"tpl1590760729373.png",
                 record_pos=(0.216, 0.426),
                 resolution=(1080, 2340)))

    time.sleep(11)
    touch(
        Template(r"tpl1590761238993.png",
                 record_pos=(-0.431, -0.948),
                 resolution=(1080, 2340)))
Esempio n. 22
0
                                # 滑动页面
                                poco("cn.com.askparents.parentchart:id/scroll"
                                     ).swipe([0.0, -0.65])

                                # 获取学校地址
                                address = poco(
                                    "cn.com.askparents.parentchart:id/text_address"
                                )
                                if address.exists():
                                    category_dict[
                                        'address'] = address.get_text()

                                school_data['category'].append(category_dict)

                        obj.add_one(collection_name, school_data)
                        print(f'Insert OK: {school_data["name"]}')

                        # 退回到列表页
                        poco(
                            "cn.com.askparents.parentchart:id/rl_title").child(
                                "cn.com.askparents.parentchart:id/img_back"
                            ).click()

            except Exception as e:
                print(f'Parse Error: {str(e)}')
                # poco("cn.com.askparents.parentchart:id/img_back").click()

    poco.swipe([1 / 2, 9 / 10], [1 / 2, 3 / 10], duration=0.2)
    time.sleep(0.1)
class DouYin():
    '''
    操作模拟器,操控软件
    '''
    def __init__(self):
        # 通过系统时间自动计算时间间隔
        a = str(datetime.now())
        hour = a.split(' ')[-1].split(':')[0]
        num = int(hour) / 3
        num = int(num) * 3
        if num == 0:  # 对于凌晨 0 点的判断
            # 时间判断部分
            date = datetime.now() - timedelta(days=1)
            news_start_time = str(date).split(' ')[0]
            yesterday = datetime.now() - timedelta(days=1)  # 昨天时间
            yesterday = str(yesterday).split(' ')[0]
        else:
            # 时间判断部分
            date = datetime.now() - timedelta(days=0)
            news_start_time = str(date).split(' ')[0]
            yesterday = datetime.now() - timedelta(days=0)  # 昨天时间
            yesterday = str(yesterday).split(' ')[0]
        print('爬取时间段:{}到{}'.format(news_start_time, yesterday))
        self.start_time = news_start_time
        # self.start_time = '2019-09-09'
        # 定义结束时间 y-m-d  离现在时间近
        self.end_time = yesterday
        # end_time = '2019-03-22'
        self.phone_name = device_name_list[0]['device_id']
        self.device_num = device_name_list[0]['device_num']
        print(self.device_num)
        self.device_1 = Android(self.device_num)
        self.poco = AndroidUiautomationPoco(self.device_1,
                                            deuse_airtest_input=True,
                                            screenshot_each_action=False)
        self.keyword_list = ['奔驰 C级', '奔驰 GLA', '奔驰 S级']
        # '宝马 X1', '宝马 X2','宝马 3系','宝马 7系', '宝马 X5', '宝马 X7',, '奔驰 GLE'
        self.size = self.poco.get_screen_size()
        self.is_break = False
        self.same_num = 0  # 表示评论数相同的计数,用来判断视频翻页是否到底
        self.up_title = ''

        pool = redis.ConnectionPool(host='127.0.0.1')  # 实现一个Redis连接池

        self.redis_example = redis.Redis(connection_pool=pool)

        self.zhu_num = 0  # 视频的翻页数,主要用来断点续爬,多少个视频之后开始采集评论

        self.is_first = True  # 是否是第一次启动的第一个关键词,主要用来断点续爬

        self.keyword = ''

    def hua(self):
        '''
        评论滑动
        :return:
        '''
        # print(size)
        x = self.size[0]
        # 获取屏幕宽
        y = self.size[1]
        self.poco.swipe([(1 / 2) * x / x, (4 / 5) * y / y], [(1 / 2) * x / x,
                                                             (1 / 4) * y / y],
                        duration=0.2)

    def first_hua(self):
        '''
        防止评论输入模式滑动
        :return:
        '''
        x = self.size[0]
        # 获取屏幕宽
        y = self.size[1]
        # # 向上滑
        self.poco.swipe([(1 / 2) * x / x, (3 / 4) * y / y], [(1 / 2) * x / x,
                                                             (1 / 6) * y / y],
                        duration=0.1)

    def hua_zhuping(self):
        '''
        视频列表页滑动
        :return:
        '''
        # 获取屏幕的高
        x = self.size[0]
        # 获取屏幕宽
        y = self.size[1]
        # 向上滑动
        # self.poco.swipe([(1 / 2) * x / x, (4 / 7) * y / y], [(1 / 2) * x / x, (3 / 7) * y / y], duration=0.1)
        self.poco.swipe([(1 / 2) * x / x, (5 / 6) * y / y], [(1 / 2) * x / x,
                                                             (1 / 6) * y / y],
                        duration=0.35)
        time.sleep(0.1)

    def hua_up(self):
        '''
        视频列表页滑动
        :return:
        '''

        # # 获取屏幕的高
        # x = self.size[0]
        # # 获取屏幕宽
        # y = self.size[1]
        # # 向上滑动
        # self.poco.swipe([(1 / 2) * x / x, (4 / 7) * y / y], [(1 / 2) * x / x, (3 / 7) * y / y], duration=0.1)
        self.poco.swipe([0.5, 0.6], [0.5, 0.8], duration=0.2)
        time.sleep(0.1)

    def is_chinese(self, uchar):
        """判断一串字符中是否有汉字"""
        for child in uchar:
            if child >= u'\u4e00' and child <= u'\u9fa5':
                return True
            else:
                continue

    def main_work(self):
        """
        这里进行滑动的逻辑操作
        :return:
        """
        for i in range(300):
            print(i)
            souye = self.poco(text='首页')
            if souye:
                return
            print('进行一次主页滑动')
            self.hua_zhuping()
            time.sleep(0.5)
            if self.poco(text='暂时没有更多了'):
                break
        # time.sleep(5)
        # self.device_1.keyevent('KEYCODE_BACK')
        # time.sleep(5)
        # self.device_1.keyevent('KEYCODE_BACK')
        # time.sleep(5)
        # self.device_1.keyevent('KEYCODE_BACK')
        # time.sleep(5)
        # self.device_1.keyevent('KEYCODE_BACK')
        # time.sleep(5)
        # self.device_1.keyevent('KEYCODE_BACK')
        print('目前返回到抖音首页.....')
        time.sleep(5)

    def input_keyword(self, keyword, num):
        """
        这里进行点击输入框,输入文本操作,并搜索
        """

        # try:
        #     print('点击输入文本框-1')
        #     search_btn = self.poco(name='com.ss.android.ugc.aweme:id/aex')[0]
        #     search_btn.click()
        #     time.sleep(1)
        # except:
        #     print('点击输入文本框-2')
        #     self.poco(name='com.ss.android.ugc.aweme:id/aex').click()
        #     time.sleep(1)
        if num > 0:
            self.poco(name='com.ss.android.ugc.aweme:id/a5j').click()
        else:
            self.poco(type='android.widget.EditText').click()
        print('输入搜索关键词')
        self.poco(type='android.widget.EditText').set_text(keyword)
        time.sleep(1)
        print('点击搜索按钮')
        self.poco(text='搜索').click()
        time.sleep(2)
        # self.poco(text='视频').click()
        # time.sleep(1)
        # self.poco.swipe([0.3, 0.3], [0.3, 0.3], duration=0.2)
        time.sleep(15)

    def time_change(self, str_time):
        """
        时间可是转换, 将‘分钟前’,‘小时前’,‘昨天’,‘前天’, '天前',转换成标准时间格式Y-m-d h:m:s
        :param str_time:
        :return:
        """
        if '秒' in str_time:
            get_time = str(datetime.now()).split('.')[0]
            return get_time

        elif '分钟' in str_time:
            get_time_num = re.search('\d{1,2}', str_time).group(0)
            get_time_num = int(get_time_num) * 60
            print(get_time_num)
            int_time = int(str(time.time()).split('.')[0]) - get_time_num
            # #转换成localtime
            time_local = time.localtime(float(int_time))
            # 转换成新的时间格式(2016-05-05 20:28:54)
            dt = time.strftime("%Y-%m-%d", time_local)  # "%Y-%m-%d %H:%M:%S"
            return dt

        elif '小时' in str_time:
            get_time_num = re.search('\d{1,2}', str_time).group(0)
            get_time_num = int(get_time_num) * 60 * 60
            print(get_time_num)
            int_time = int(str(time.time()).split('.')[0]) - get_time_num
            # #转换成localtime
            time_local = time.localtime(float(int_time))
            # 转换成新的时间格式(2016-05-05 20:28:54)
            dt = time.strftime("%Y-%m-%d", time_local)  # "%Y-%m-%d %H:%M:%S"
            return dt

        elif '昨天' in str_time:
            try:
                part_time = str_time.split(' ')[1]
                yesterday = datetime.now() - timedelta(days=1)  # 昨天时间
                yesterday = str(yesterday).split(' ')[0]
            except:
                yesterday = datetime.now() - timedelta(days=1)  # 昨天时间
                yesterday = str(yesterday).split(' ')[0]
            return yesterday

        elif '前天' in str_time:
            part_time = str_time.split(' ')[1]
            two_days_ago = datetime.now() - timedelta(days=2)  # 昨天时间
            two_days_ago = str(two_days_ago).split(
                ' ')[0] + ' ' + part_time.replace('点', ':').replace('分', '')
            return two_days_ago

        elif '天前' in str_time:
            part_time = str_time.split('天前')[0]
            two_days_ago = datetime.now() - timedelta(
                days=int(part_time))  # 昨天时间
            two_days_ago = str(two_days_ago).split(' ')[0]
            return two_days_ago

        elif '年' in str_time:
            str_time = str_time.replace('年',
                                        '-').replace('月',
                                                     '-').replace('日', '')
            return str_time
        else:
            # str_time = '2019-' + str_time.replace('月', '-').replace('日', '')
            return str_time

    def run(self):

        self.homing()

        # if not self.poco(text='首页'):
        #     self.device_1.shell('input keyevent 26')
        #     time.sleep(1)
        #     self.poco.swipe([0.5, 0.9], [0.5, 0.4], duration=0.3)
        #     time.sleep(5)
        # try:
        #     self.poco(name='com.ss.android.ugc.aweme:id/ap1').click()
        #     print('点击搜索按钮-1')
        #     time.sleep(1)
        # except:
        #     print(traceback.format_exc())
        #     print('点击搜索按钮-2')
        #     self.poco(name='com.ss.android.ugc.aweme:id/agt').click()
        #     time.sleep(1)
        keyword_list = eval(self.redis_example.get('keyword_list'))
        print(type(keyword_list))
        # for keyword in self.keyword_list:
        for i in range(1000):  # 通过将关键词存入rides中,然后各个爬虫实例来取
            # self.homing()
            time.sleep(5)
            keyword_index = int(self.redis_example.get('keyword_index'))
            if keyword_index > len(keyword_list):  # 判断关键词是否爬取完毕
                print('关键词爬取完毕......,最后一个爬取关键词为:', self.keyword)
                break
            self.keyword = keyword_list[keyword_index]
            print('获得关键词:', self.keyword)
            keyword_index += 1
            self.redis_example.set('keyword_index', keyword_index)
            self.redis_example.set(self.phone_name, self.keyword)
            # time.sleep(30)
            print(111111,
                  self.redis_example.get(self.phone_name).decode('utf8'))
            # try:
            if i == 0:

                self.poco(desc='搜索').click()
                # except:
                #     time.sleep(10)
                #     self.device_1.keyevent('KEYCODE_BACK')
                #     time.sleep(10)
                #     self.poco(desc='搜索').click()
                time.sleep(10)
                self.input_keyword(self.keyword, i)  # 输入关键词
                self.main_work()  # 活动操作
            else:
                self.input_keyword(self.keyword, i)  # 输入关键词
                self.main_work()  # 活动操作

    def homing(self):

        for i in range(6):
            souye = self.poco(text='关注')
            if not souye:
                self.device_1.keyevent('KEYCODE_BACK')
                time.sleep(5)
            else:
                print('返回到首页.....')
                time.sleep(20)
                break
Esempio n. 24
0
#elem = poco(name='android.widget.TextView')

title_set = set()
time.sleep(5)

for i in range(3):
    ls = poco(name='com.xingin.xhs:id/qd')
    if not ls.exists():
        break
    for each in ls:
        each.click()
        close_btn_ad = poco(name='android.view.View')
        if close_btn_ad.exists():
            close_btn_ad.click()

        poco.swipe([0.5, 0.8], [0.5, 0.3])
        # 提取标题
        title = poco(name='com.xingin.xhs:id/bdk')
        if title.exists():
            title = title.get_text()
        else:
            title = '空'
        if title == '空' or title not in title_set:
            print('title:', title)

            # 提取昵称
            author = poco(name='com.xingin.xhs:id/nickNameTV')
            if author.exists():
                author = author.get_text()
            else:
                author = poco(name='com.xingin.xhs:id/matrixNickNameView')
Esempio n. 25
0
class TaoBao(object):
    def __init__(self, key, *args):
        self.poco = AndroidUiautomationPoco(screenshot_each_action=False)

        auto_setup(__file__)

        # 搜索关键字
        self.key = key

        # 浏览商品详情的时间,默认时长为20s
        if len(args) == 1 or len(args) == 2:
            self.browser_detail_time = args[0]
        else:
            self.browser_detail_time = 20

        # 浏览评论的时长,默认时长为5s
        self.browser_evalute_time = args[1] if len(args) == 2 else 5

        # 待匹配的商品主图
        self.main_img_path = ''

    def run(self):
        # 1、准备工作,打开淘宝客户端
        self.__pre()

        # 2、根据关键字,搜索商品
        self.__search_good_by_key()

        # 3、剪切图片,拿到商品主图
        self.main_img_path = crop_main_img('./333.jpeg')

        # 4、滑动,从列表中匹配商品
        self.__search_good_from_list()

        # 5、收藏商品
        self.__collect_good()

        # 6、浏览商品
        self.__browser_good_detail()

        # 7、查看评论
        self.__browser_good_evalute()

        # 8、购买
        self.__buy_good()

        # 9、获取订单编号
        order_no = self.__get_order_no()

        # 10、截取订单截图页面
        screenshot_pic_result = self.get_order_pic()

        print(f'购买完成!\n订单号为:{order_no}\n订单截图路径:{screenshot_pic_result}')

    def __collect_good(self):
        """
        收藏商品
        :return:
        """
        # 滑动一次,使顶部Tab显示出来
        self.__swipe(True)
        self.__swipe(True)

        # 判断商品是否收藏
        fav_element = self.poco('com.taobao.taobao:id/fav_title')

        if fav_element.get_text() == '收藏':
            print('开始收藏...')
            fav_element.parent().children()[0].click()
            back_keyevent()
        else:
            print('商品已经收藏')

    def __pre(self):
        """
        准备工作
        :return:
        """
        # 删除缓存文件
        remove_cache('./part.jpg', './screenshot.png', './uidump.xml')

        home()
        stop_app(package_name)
        start_my_app(package_name, activity)

    def __search_good_by_key(self):
        """
        通过关键字搜索商品
        :return:
        """
        self.poco(id_page_main_button_search).wait(5).click()
        # perform_view_id_click(poco, id_page_main_button_search)
        perform_view_input(self.poco, id_page_search_edittext_search, self.key)

        # 点击搜索
        self.poco(id_page_search_button_search).wait_for_appearance()
        while self.poco(id_page_search_button_search).exists():
            print('点击一次搜索')
            perform_view_id_click(self.poco, id_page_search_button_search)

        # 等待列表加载出来
        self.poco(id_page_goods_rv).wait_for_appearance()

    def __search_good_from_list(self):
        """
        从列表中匹配商品
        :return:
        """
        # 循环的图片查找
        while True:
            try:
                pos = loop_find(Template(self.main_img_path),
                                timeout=10,
                                threshold=0.95)
            except TargetNotFoundError:
                print('滑动一页')
                # self.poco.swipe([0.5, 0.8], [0.5, 0.4], duration=0.2)
                self.__swipe(True)
            else:
                print('找到了')
                # poco.click([100.0 / 1920, 100.0 / 1080])

                print(pos)

                # 屏幕宽度和高度
                screen_size = self.poco.get_screen_size()
                print(screen_size)

                # 点击的坐标点(宽、高)
                # (0.22407407407407406, 0.8550925925925926)
                position_click = (pos[0] / screen_size[0],
                                  pos[1] / screen_size[1])
                print(position_click)
                self.poco.click(position_click)
                break

    def __swipe(self, up_or_down):
        """
        滑动单条新闻
        :param up_or_down: true:往上滑动;false:往下滑动【慢慢滑动】
        :return:
        """
        if up_or_down:
            self.poco.swipe([0.5, 0.8], [0.5, 0.4], duration=0.2)
        else:
            self.poco.swipe([0.5, 0.4], [0.5, 0.8], duration=0.2)

    def __browser_good_detail(self):
        """
        浏览商品
        :return:
        """
        # 切换到详情Tab
        self.poco('com.taobao.taobao:id/taodetail_nav_bar_tab_text',
                  text='详情').click()

        # 滑动时长为: self.browser_detail_time
        browser_start = datetime.datetime.now()
        browser_end = browser_start

        while (browser_end - browser_start).seconds < self.browser_detail_time:
            # 休眠一会
            time.sleep(random.randint(2, 5))

            # 滑动一次
            self.__swipe(True)

            # 结束时间
            browser_end = datetime.datetime.now()

        print('详情页面查看完毕')

    def __browser_good_evalute(self):
        """
        查看评论
        :return:
        """
        print('查看评论')
        # 切换到详情Tab
        self.poco('com.taobao.taobao:id/taodetail_nav_bar_tab_text',
                  text='评价').click()

        # 查看全部评论
        self.poco('com.taobao.taobao:id/mainpage').offspring(
            text='查看全部').click()

        browser_start = datetime.datetime.now()
        browser_end = browser_start

        while (browser_end -
               browser_start).seconds < self.browser_evalute_time:
            # 休眠一会
            time.sleep(random.randint(2, 5))

            # 滑动一次
            self.__swipe(True)

            # 结束时间
            browser_end = datetime.datetime.now()

        print('评价页面查看完毕')

    def __buy_good(self):
        """
        购买商品
        :return:
        """
        # 立即购买
        self.poco('com.taobao.taobao:id/detail_main_sys_button',
                  text='立即购买').click()

        # 选择商品属性
        sleep(10)

        # 确定购买
        self.poco('com.taobao.taobao:id/confirm_text',
                  text='确定').parent().click()

        # 提交订单
        self.poco(text='提交订单').click()

        # 手动输入密码或者指纹
        sleep(10)

    def __get_order_no(self):
        """
        获取订单编号
        :return:
        """
        global copy_element
        while True:
            # 由于手机屏幕的限制,【复制】按钮第一页不一定能显示出来

            try:
                copy_element = self.poco(text='复制')
            except Exception as e:
                print('没有找到元素,往下滑动一页')
                self.__swipe(True)

            break

        copy_element.click()

        # 从剪切板拿到数据
        result = exec_cmd('adb shell am broadcast -a clipper.get')[1]

        # 匹配出订单号
        result = re.findall(r'data="(.*)"', result)

        order_no = ''

        if result and len(result) > 0:
            order_no = result[0]

        print(order_no)

        return order_no

    def get_order_pic(self):
        """
        拿到订单截图界面
        :return:
        """
        screenshot_pic_result = './order_screenshot.png'

        # 截取手机当前屏幕
        exec_cmd('adb shell /system/bin/screencap -p /sdcard/screenshot.png')

        # 保存到PC端
        exec_cmd('adb pull /sdcard/screenshot.png %s' % screenshot_pic_result)

        return screenshot_pic_result
Esempio n. 26
0
# -*- encoding=utf8 -*-
__author__ = "chenwt"

from airtest.core.api import *

auto_setup(__file__)

from poco.drivers.android.uiautomation import AndroidUiautomationPoco
poco = AndroidUiautomationPoco(use_airtest_input=True, screenshot_each_action=False)
#exec_script("test_custom_info.air")
point1 = poco(text = "是否预约").get_position()
point2 = poco(text = "顾客姓名").get_position()
poco.swipe(point1,point2)
# point3 = poco(text = "接待备注").get_position()
# point4 = poco(text = "联系地址").get_position()
# poco.swipe(point3,point4)
try:
    is_sign=poco("com.iris.lshitaskse:id/tv_intention_1").get_text()
except Exception as e:
    is_sign = ''
if is_sign != "意向一":
    poco("com.iris.lshitaskse:id/tv_name_type").click()
    poco("com.iris.lshitaskse:id/tv_intention_car_model").click()
else:  poco("com.iris.lshitaskse:id/tv_intention_car_model").click()
    
point3 = poco("com.iris.lshitaskse:id/listview").child("android.widget.FrameLayout")[4].get_position()

#print('P1:',point4)
point4 = poco("com.iris.lshitaskse:id/listview").child("android.widget.FrameLayout")[1].get_position()
#print('p2:',point3)
#sleep(3)
Esempio n. 27
0
class EastNews(object):
    """
    东方头条的自动化薅羊毛
    """
    def __init__(self):
        self.package_name = "com.songheng.eastnews"
        self.conn()

    def conn(self):
        self.poco = AndroidUiautomationPoco()

    def run(self):

        home()
        start_app(self.package_name)

        self.__pre_skip_ads()
        print("进入主页")

        # 获取顶部的金币
        self.get_top_title_coin()

        self.normal_task()

    def __pre_skip_ads(self):
        """ 预加载,跳过广告,进入主页
        1. 等待广告出现
        2. 点击跳过广告
        3. 等待首页元素加载完成
        :return:
        """

        # 有广告则点击跳过
        ads_element = self.poco(name='android.widget.TextView',
                                text='跳过').wait(10).click()

        # 等待主页显示
        self.poco('com.songheng.eastnews:id/fu').wait_for_appearance(120)

    def get_top_title_coin(self):
        """
        获取顶部金币
        :return:
        """

        top_coin = self.poco(name="com.songheng.eastnews:id/arc", text="领取")
        if top_coin.exists():
            print("点击领取金币")
            top_coin.click()

            # 关闭广告
            self.poco(name="com.songheng.eastnews:id/go").click()
        else:
            print("时间不足或者不在首页")

    def normal_task(self):
        """
        日常任务

        1. 签到
        2. 大转盘
        :return:
        """
        pass

    def watch_news(self):
        """
        看新闻。 看一个小时先试试水
        :return:
        """

        while True:
            news_list = self.poco("com.songheng.eastnews:id/go").children()

            # 如果没有元素,则往下翻页
            if not news_list.exists():
                self.next_page()
                continue

            for news in news_list:
                news_title = news.offspring("com.songheng.eastnews:id/pn")
                news_foot = news.offspring("com.songheng.eastnews:id/a5a")

                # 必须是完整的一条内容才打开,否则跳过
                if not news_title.exists() or not news_foot.exists():
                    print("内容不完整..切换下一条新闻")
                    continue

                if news.offspring("com.songheng.eastnews:id/a5k").exists():
                    print("视频跳过")
                    continue

                # 如果是小视频,跳过
                if news.offspring("com.songheng.eastnews:id/a7a").exists():
                    # print("小视频,跳过")
                    self.play_small_video()
                    backup_keyevent()
                    continue

                # 广告跳过
                if news.offspring("com.songheng.eastnews:id/a5i").exists():
                    print("广告,跳过")
                    continue

                # 下载软件的广告,跳过
                if news.offspring("com.songheng.eastnews:id/a0a").exists():
                    print("下载广告,跳过")
                    continue

                if news.offspring("com.songheng.eastnews:id/a4n").exists():
                    self.play_video()
                    backup_keyevent()
                    continue

                print("正在看 {}".format(news_title.get_text()))

                news_title.click()

                try:
                    self.play_news()
                except Exception as e:
                    print("读取新闻时出现异常 = {}".format(str(e)))
                    self.conn()
                    exit(-1)

                print("返回")
                backup_keyevent()

            self.next_page()

        print("新闻结束..")

    def play_news(self):
        max_times = random.randint(5, 15)
        now_times = 0

        while True:

            start_point = random.uniform(0.6, 0.9)
            end_point = random.uniform(0.9, 0.7)
            duration = round(random.uniform(4, 5), 2)
            self.poco.swipe([start_point, end_point],
                            [start_point, end_point - 0.6],
                            duration=2)

            # 点击查看全文
            click_all = self.poco("点击查看全文")
            if click_all.exists():
                click_all.click()

            # 如果遇到广告, 说明该文章已经读完,可以退出来了
            if self.poco("相关推荐 ").exists():
                break

            # 看会儿新闻
            see_time = round(random.uniform(0.8, 1.5), 2)
            print("see_time = {}".format(see_time))
            time.sleep(see_time)

            # 下滑次数超过最大次数,则退出该新闻
            if now_times == max_times:
                print("超过次数,退出新闻")
                break
            now_times += 1

        print("看完这篇新闻")

    def watch_video(self):
        """
        看视频
        :return:
        """

        # self.poco(name="com.songheng.eastnews:id/js", text="视频").click()

        while True:
            video_elements = self.poco(
                name="com.songheng.eastnews:id/a0z").children()
            for video_element in video_elements:

                # 如果是广告则跳过
                if video_element.offspring(
                        "com.songheng.eastnews:id/a_g").exists():
                    print("视频右下角广告跳过")
                    continue

                # 如果没有标题,则跳过
                video_text = video_element.offspring(
                    "com.songheng.eastnews:id/ot")
                video_content = video_element.offspring(
                    "com.songheng.eastnews:id/a4d")
                if not video_text.exists() or not video_content.exists():
                    print("标题或者正文视频至少有一个不存在")
                    continue

                print("正在看 {}".format(video_text.get_text()))

                # 打开视频
                video_content.click()

                try:
                    self.play_video()
                except Exception as e:
                    print("出异常 = {}".format(traceback.format_exc()))
                    self.conn()
                    continue

                print("返回")
                backup_keyevent()

            self.close_push_news()
            self.next_page()

    def play_video(self):
        """
        开始播放视频
        :return:
        """

        print("开始看视频")
        start_time = datetime.datetime.now()
        watch_time = random.randint(30, 50)

        while True:

            # 出现重播,已经播放完,退出视频
            if self.poco("com.songheng.eastnews:id/aqh").exists():
                break

            end_time = datetime.datetime.now()

            # 播放到一定时间就退出视频
            if (end_time - start_time).seconds > watch_time:
                print("播放时间超时, 需要退出视频")
                break

            # 看视频的过程中,关闭推送的新闻
            self.close_push_news()

        print("看完视频了..")

    def play_small_video(self):

        print("开始看小视频")
        start_time = datetime.datetime.now()

        # 是视频最大时间
        max_seconds = random.randint(10, 20)

        while True:

            end_time = datetime.datetime.now()

            if (end_time - start_time).seconds > max_seconds:
                break

        print("看完小视频")

    def next_page(self):

        print("下一页")
        start_point = round(random.uniform(0.2, 0.6), 2)
        end_point = round(random.uniform(0.7, 0.9), 2)
        duration = round(random.uniform(0.5, 0.8), 2)
        self.poco.swipe([start_point, end_point],
                        [start_point, end_point - 0.6],
                        duration=duration)

    def lottery(self):
        # self.poco(name="com.songheng.eastnews:id/jv").click()
        # self.poco(name="com.songheng.eastnews:id/mv", text="幸运转盘").wait(10).click()

        i = 0
        while i < 20:
            self.poco(name="J_gift").wait(5).click()

            try:
                click_gain = self.poco(name="gainBtn", desc="立即领取").wait(10)
                if click_gain.exists():
                    click_gain.click()
                else:
                    self.poco(name="gainBtn", text="立即翻倍").wait(5).click()

                print("开始转动..")
            except Exception as e:
                print(str(e))
                try:
                    self.poco(
                        name="com.songheng.eastnews:id/apj").wait(5).click()
                    print("关闭广告")
                except Exception as e:
                    print("看视频")
                    self.poco(name="gainBtn").click()
                    time.sleep(40)

                    # 关闭视频广告
                    adv_close = self.poco(
                        name="com.songheng.eastnews:id/go").wait(5)
                    if adv_close.exists():
                        adv_close.click()
                    else:
                        self.poco(
                            name="com.songheng.eastnews:id/tt_video_ad_close"
                        ).wait(5).click()

                    self.poco(name="gainBtn").wait(5).click()

    def close_push_news(self):

        if self.poco("com.songheng.eastnews:id/x8").exists():
            print("遇到推送新闻,退出")
            self.poco("com.songheng.eastnews:id/wz").click()
Esempio n. 28
0
    #text("130768877665243565")
    text(config.get_id_card())
    poco("com.iris.dch.itask:id/title").child(
        "android.widget.TextView")[1].click()
    poco("com.iris.dch.itask:id/tv_province").click()
    poco(text="北京市").click()
    poco("com.iris.dch.itask:id/tv_city").click()
    poco(text="北京市").click()
    poco("com.iris.dch.itask:id/tv_canton").click()
    poco(text="东城区").click()
    poco("com.iris.dch.itask:id/tv_address").click()
    text("jhssdferweirufidsf")
    poco("com.iris.dch.itask:id/title").child(
        "android.widget.TextView")[1].click()
    #滑动展示出车辆信息按钮--由于手机分辨率问题这样有问题导致不同手机滑动不能展示出来
    poco.swipe([0.5, 0.8359375], [0.5, 0.145625])
    poco(text="车辆").click()
    poco(text="车辆信息").click()
    poco("com.iris.dch.itask:id/rb_intent1").click()
    poco(text="车辆信息").click()
    poco.swipe([0.5, 0.8359375], [0.5, 0.245625])
else:
    poco("com.iris.dch.itask:id/tv_add").click()
    poco("com.iris.dch.itask:id/tv_id_card").click()
    #text("130768877665243565")
    text(config.get_id_card())
    poco("com.iris.dch.itask:id/title").child(
        "android.widget.TextView")[1].click()
    poco("com.iris.dch.itask:id/tv_province").click()
    poco(text="北京市").click()
    poco("com.iris.dch.itask:id/tv_city").click()
Esempio n. 29
0
from Search import Search
from ShortVideo import ShortVideo
from Member import Member
from LongVideo import LongVideo
from Login import Login
using("F:/aritest/ppWx/public")
from fun import SearchToLongvideo,quit,swipeStartIndex
using("F:/aritest/ppWx/conf")
from Conf  import accoutConf

poco = AndroidUiautomationPoco(use_airtest_input=True, screenshot_each_action=False)


if(poco(text = "首页").exists() == False):
    poco(text = "微信").click()
    poco.swipe([0.5, 0.4], [0.5, 0.8], duration = 1)
    poco(text = "PP视频").click()

login = Login('weixin')
longVideo = LongVideo()

def  checkResult(data, msg = ''):
    for key in data:
        try:
            assert_equal(data[key], True, msg + '--【' + key + '】')
        except:
            print('------')
            pass
# 3、VIP用户-不同类型视频-播放器展示场景
ppLoginRes = login.ppLogin(accoutConf['vipUser'], 1)
#退到--首页
poco = AndroidUiautomationPoco(use_airtest_input=True,
                               screenshot_each_action=False)
#功能:切换比例保存图片:
#步骤:首页点击图片标记--滑动相册页--点击一张图片--点击制作--点击编辑--切换比例3:4--点击完成--点击保存--验证保存成功--点击返回首页
# def switchRatioAndSavePhoto(self):
#     poco( text="图片标记" ).click()
#     poco.swipe( [0.5, 0.7], [0.5, 0.3] )
#     sleep( 5 )
#     poco.click( [0.4, 0.4] )
#     poco( text="制作" ).click()
#     poco( text="编辑" ).click()
#     poco( text="3:4" ).click()
#     poco( text="完成" ).click()
#     poco( text="保存" ).click()
#     assert_exists(Template(r"tpl1562829085071.png", record_pos=(0.015, -0.099), resolution=(1080, 2160)), "切换比例测试")
#     poco( text="返回首页").click()
poco(text="图片标记").click()
poco.swipe([0.5, 0.7], [0.5, 0.3])
sleep(5)
poco.click([0.4, 0.4])
poco(text="制作").click()
poco(text="编辑").click()
poco(text="3:4").click()
poco(text="完成").click()
poco(text="保存").click()
assert_exists(
    Template(r"tpl1562829085071.png",
             record_pos=(0.015, -0.099),
             resolution=(1080, 2160)), "切换比例测试")
poco(text="返回首页").click()