解放双手,自动刷抖音

起因

因为项目需要,最近在学习appium自动化,学习中很枯燥无味,想做点能激起兴趣的事情,正好平时喜欢刷抖音,想一想能不能解放双手自动刷抖音呢,有想法咱们就行动起来,搞、搞、搞

(ps:代码很简单,就是环境比较难搭建)

一、环境搭建:

1、我使用的环境:

①、Python3.7
②、Node.js14.9.0
③、JDK1.8
④、Andriod SDK
⑤、Appium1.9.1
⑥、Appium-Python-Client

上面是我使用的环境,安装过程就不一一解释了,学习appium最大的难处在于环境的安装,80%的人死于环境安装,然后就没然后了,10%的人被环境折腾一周以上,只有剩下的10%人品好,可以顺利安装。小伙伴们一定不能在环境搭建上面放弃哦,加油,奥利给!

附上软件包下载地址:
链接:https://pan.baidu.com/s/1n7C6-3r5f68oJbBkDuX_jQ
提取码:82wi

二、启动APP

1、连接手机:
手机设置开发者模式---->允许USB调试---->cmd中输入adb devices---->显示如下图表示连接成功:
在这里插入图片描述

2、获取包名和Activity名:
①、打开需要用的app
②、在cmd中输入:adb shell dumpsys window w |findstr / |findstr name= 后如图展示:
解放双手,自动刷抖音_第1张图片
③、包名和Activity名为:com.ss.android.ugc.aweme/com.ss.android.ugc.aweme.splash.SplashActivity

3、启动app参数:

desired_caps = {}
desired_caps['platformName'] = 'Android'   #你要测试的手机操作系统|`iOS`, `Android`, 或 `FirefoxOS`|
desired_caps['platformVersion'] = '10'     #手机操作系统版本|例如: `7.1`, `4.4`|
desired_caps['deviceName']='JTK5T19917008667'  #手机设备名称
desired_caps['appPackage'] = 'com.ss.android.ugc.aweme'   #你想运行的Android应用的包名
desired_caps['appActivity'] = 'com.ss.android.ugc.aweme.splash.SplashActivity
'  #你要从你的应用包中启动的 Android Activity 名称
desired_caps['automationname']='UiAutomator2'   #安卓7以上设备启动时必须加上此参数,定位toast提示时也必须加
desired_caps['noReset']='True' #用来防止重复安装app

4、启动app:

driver = webdriver.Remote('http://127.0.0.1:4723/wd/hub', desired_caps)

5、为了方便后期维护,写成配置封装下:

①、获取配置文件代码:
配置文件名字可以是.cfg或者.ini结尾文件,如图:
解放双手,自动刷抖音_第2张图片

#coding:utf-8
import os
from configparser import ConfigParser
"""
获取descaps.cfg配置文件里面数据
"""
class Dictionary(dict):
    '''
    把descaps.cfg中的参数添加值dict
    '''
    def __getattr__(self, keyname):
        #如果key值不存在则返回默认值"not find config keyname"
        return self.get(keyname, "descaps.cfg中没有找到对应的keyname")

class Config(object):
    '''
    ConfigParser二次封装,在字典中获取value
    '''
    def __init__(self):
        # 设置descaps.cfg路径
        current_dir = os.path.dirname(__file__)
        top_one_dir = os.path.dirname(current_dir)
        file_name = top_one_dir + "/data/descaps.cfg"
        # 实例化ConfigParser对象
        self.config = ConfigParser()
        self.config.read(file_name)
        #根据section把key、value写入字典
        #print(self.config.sections())
        for section in self.config.sections():
            setattr(self, section, Dictionary())
            #print(self.config.items(section))
            for keyname, value in self.config.items(section):
                setattr(getattr(self, section), keyname, value)

    def getconf(self, section):
        '''
        用法:
        conf = Config()
        info = conf.getconf("main").url
        '''
        if section in self.config.sections():
            pass
        else:
            print("文件中 找不到该 section")
        return getattr(self, section)

②、启动APP封装代码:

#coding=utf-8
from appium import webdriver
from tools.configoperate import Config
import os

class BasicSetting(object):
    def __init__(self,conf_section):
        """
        初始化启动appium参数配置
        :param conf_section: descaps.cfg文件中的每个配置项的section值
        :param platformname 使用哪个移动操作系统平台
        :param devicename   使用的移动设备或模拟器的种类,需要在cmd命令下,敲adb devices查看
        :param platformversion  移动操作系统版本
        :param apppackage   所要测试的app的包名,获取命令:aapt dump badging apk路径,查看package
        :param appactivity  所要测试app的入口页面,获取命令:aapt dump badging apk路径,查看launchable-activity
        :param unicodekeyboard
        :param noreset     在此会话之前,请勿重置应用程序状态
        """
        conf = Config()
        info = conf.getconf(conf_section)
        self.automationname = info.automationname
        self.platformname = info.platformname
        self.devicename = os.popen('adb shell getprop ro.product.model').read()
        self.platformversion = os.popen('adb shell getprop ro.build.version.release').read()
        self.apppackage = info.apppackage
        self.appactivity = info.appactivity
        self.noreset = info.noreset



    def start_parameter(self):
        desired_caps={
            'automationName':self.automationname,
            'platformName':self.platformname,
            'deviceName':self.devicename,
            'platformVersion':self.platformversion,
            'appPackage':self.apppackage,
            'appActivity':self.appactivity,
            'noReset':self.noreset
        }
        #连接appium server,把启动参数发送
        self.driver = webdriver.Remote('http://127.0.0.1:4723/wd/hub',desired_caps)
        try:
            # 设置手机默认输入法为ADB keyboard
            os.system('adb shell ime set com.android.adbkeyboard/.AdbIME')
        except Exception as e:
            print(e)
            print("手机可能未安装ADB keyboard输入法")

        return self.driver

上面我们讲了启动app需要哪些参数和条件,可能会因版本和手机不一样有一些出入,导致启动不了app,具体问题欢迎大家留言讨论

三、进入app,自动滑动页面

1、滑动页面:

①、appium官方给我提供的方式是:

swipe(self, start_x, start_y, end_x, end_y, duration=None)
    从一个点滑动到另外一个点
    start_x 是开始滑动的x坐标, start_y 是开始滑动的y坐标
    end_x 是结束点x坐标,end_y是结束点y坐标
    duration是持续时间,单位毫秒,可以不填,一般设置为500-1000之间

我们根据使用封装了下滑动的使用如下:

class SwipePlace(object):
    """操作app上滑动、下滑、左滑、右滑"""
    def __init__(self,driver):
        self.driver = driver
    def get_size(self):
        """获取手机屏幕大小"""
        x = self.driver.get_window_size()['width']
        y = self.driver.get_window_size()['height']
        return (x,y)

    def swipe_up(self,dt=500):
        """向上滑动"""
        screen = self.get_size()
        sx = screen[0] * 0.5
        sy = screen[1] * 0.75
        ex = screen[1] * 0.5
        ey = screen[1] * 0.25
        self.driver.swipe(sx, sy, ex, ey,dt)

    def swipe_down(self,dt=50):
        """向下滑动"""
        screen = self.get_size()
        sx = screen[0] * 0.5
        sy = screen[1] * 0.25
        ex = screen[0] * 0.5
        ey = screen[1] * 0.75
        self.driver.swipe(sx, sy, ex, ey, dt)

    def swipe_left(self,dt=50):
        """向左滑动"""
        screen = self.get_size()
        sx = screen[0] * 0.75
        sy = screen[1] * 0.5
        ex = screen[0] * 0.25
        ey = screen[1] * 0.5
        self.driver.swipe(sx, sy, ex, ey, dt)

    def swipe_right(self,dt=50):
        """向右滑动"""
        screen = self.get_size()
        sx = screen[0] * 0.25
        sy = screen[1] * 0.5
        ex = screen[0] * 0.75
        ey = screen[1] * 0.5
        self.driver.swipe(sx, sy, ex, ey, dt)

3、自动滑动douyin app页面
上面讲了那么多,就是为了下面一个循环做准备,下面代码很简单,就是循环滑动页面,调用我们上面写的代码,如下:

#coding=utf-8
from time import sleep
from common.basicMessage import BasicSetting
from tools.swipeplace import SwipePlace

driver = BasicSetting("douyin").start_parameter()
swi = SwipePlace(driver)

for i in range(1,10000):
    swi.swipe_up()
    sleep(10)

driver.quit()

咱们就少循环点,保护眼镜最重要,哈哈哈,到此自动刷视频咱们就完成了,这次只做了简单的刷视频,一个视频的等待时间可以自己控制,后面有空继续优化下,下面我们看看效果,视频上传了B站,可能有点模糊。

视频地址.
https://www.bilibili.com/video/BV1o5411P7SS/

你可能感兴趣的:(Python学习之路,python,app,android,安卓)