UiAutomator2+weditor+python获取抖音直播间评论


UiAutomator2+weditor+python获取抖音直播间评论

终极目标:获取抖音直播时评论数据

准备工作:

  1. android手机或模拟器(无需root)
  2. python环境

开始:

1. 设备连接

  • android手机打开开发者模式
  • USB连接电脑,允许USB调试
  • 命令行输入 adb devices 查看设备

2. 安装UiAutomator2

  • 确保python环境正常,使用 pip3 install -U uiautomator2 安装UiAutomator2

3. 安装httprpc服务

  • 运行 python -m uiautomator2 init 安装apk到手机

4. 安装weditor

  • 运行 pip3 install --pre -U weditor 安装weditor在线元素查看器

5. 使用weditor查看界面元素

  • 执行 weditor 打开浏览器并连接设备,查看界面元素树

6. 编写脚本获取评论列表文本内容

# -*- coding: utf-8 -*-
# @Time    : 2024/6/17 22:22
# @Author  : Kylin
# @File    : douy.py
# @Software: PyCharm


# coding=utf8
from collections import OrderedDict

import uiautomator2 as u2
import time
import logging
import re
import json
from string import Template


class UniqueOrderedList:
    def __init__(self):
        self.items = OrderedDict()

    def add(self, item):
        if item not in self.items:
            self.items[item] = None

    def get_items(self):
        return list(self.items.keys())


# 示例使用
unique_list = UniqueOrderedList()

d = u2.connect('192.168.3.25:5555')
d.click_post_delay = 1.5  #

logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(name)s - %(funcName)s - %(message)s')
logger = logging.getLogger(__name__)
logger.info(d)


def run_app():
    d.app_start("com.ss.android.ugc.aweme")  # 打开程序
    if d.session("com.ss.android.ugc.aweme", attach=True):  # 判断程序是否打开
        logger.info("已打开程序")
        if d(text="更多直播").exists(timeout=5):  # exists:等待元素出现
            logger.info("当前是打开状态״̬")
            # //*[@resource-id="com.ss.android.ugc.aweme:id/ot6"]
            #
            # print("size:",
            #       d.xpath('//*[@resource-id="com.ss.android.ugc.aweme:id/text"]').all())

            for s in d.xpath('//*[@resource-id="com.ss.android.ugc.aweme:id/text"]').all():
                unique_list.add(s.text)

            for u in unique_list.get_items():
                print(str(u))




        else:
            logger.info("未找到指定文本״̬")
    else:
        print('app打开错误')


while True:
    print('------获取当前屏幕评论数据------')
    run_app()
    time.sleep(1)