from airtest.core.api import *
import time
import random
class DouyinAuto(AirtestController):
"""抖音自动化类,继承基础双引擎控制器"""
# 抖音不同渠道包名可能不同:通过adb shell pm list packages -3查找
DOUYIN_PKG = "com.ss.android.ugc.aweme"
def launch(self):
"""启动抖音并等待首页「推荐」标签加载完成"""
try:
start_app(self.DOUYIN_PKG)
# 首页加载等待时间稍长,适配网络波动
self.wait_for_text("推荐", timeout=20)
print("📱 抖音首页加载完成")
return True
except Exception as e:
print(f"❌ 抖音启动失败:{str(e)}")
return False
def random_like(self):
"""70%概率点赞:优先图像识别,通用坐标兜底"""
if random.random() > 0.7:
return
try:
# 优先识别未点赞的爱心图标
if exists(Template("like_btn.png", threshold=0.7)):
touch(Template("like_btn.png"))
else:
# 兜底:主流手机抖音右侧爱心的通用坐标
w, h = device().get_current_resolution()
touch((w*4//5, h//2 + 100 + random.randint(-20, 20)))
print("❤️ 随机点赞成功")
time.sleep(random.uniform(0.3, 0.7))
except:
pass
def random_comment(self, comments=None):
"""20%概率评论:从预设/用户自定义列表随机选内容"""
if random.random() > 0.2:
return
default_comments = ["不错👍", "学到了", "666", "收藏了", "好看!", "太真实了"]
comment = random.choice(comments or default_comments)
w, h = device().get_current_resolution()
try:
# 点击右侧评论图标(通用坐标带随机偏移)
touch((w*4//5, h//2 + 200 + random.randint(-20, 20)))
time.sleep(random.uniform(1.5, 2.5))
# 点击底部输入框
touch((w//2 + random.randint(-50, 50), h*5//6))
time.sleep(random.uniform(0.8, 1.2))
# 输入评论
text(comment)
time.sleep(random.uniform(0.3, 0.7))
# 点击右侧发送按钮
touch((w*9//10 + random.randint(-20, 20), h*5//6))
print(f"💬 随机评论成功:{comment}")
time.sleep(random.uniform(1.5, 2.5))
# 返回视频页
keyevent("BACK")
time.sleep(random.uniform(0.8, 1.2))
except:
# 出错直接返回,避免脚本卡住
keyevent("BACK")
time.sleep(random.uniform(0.5, 1))
def run(self, cycles=5):
"""运行指定次数的交互循环"""
if not self.launch():
return
print(f"\n🤖 开始执行 {cycles} 次抖音交互循环...\n")
for i in range(cycles):
print(f"🔄 第 {i+1} 次循环:")
# 随机点赞
self.random_like()
# 随机评论
self.random_comment()
# 刷下一个视频
self.swipe_up()
# 随机等待3-6秒,模拟真人浏览速度(避风控核心!)
wait_time = random.uniform(3, 6)
print(f"⏳ 等待 {wait_time:.1f} 秒\n")
time.sleep(wait_time)
print("🏁 所有循环执行完毕!")
stop_app(self.DOUYIN_PKG)
# 生成可视化HTML测试报告
from airtest.report.report import simple_report
simple_report(__file__, logpath=True, output="douyin_auto_report.html")
# 测试脚本入口
if __name__ == "__main__":
douyin = DouyinAuto()
douyin.run(cycles=3)