終極目標:獲取抖音直播時評論資料,
準備作業:
1. android手機或模擬器(無需root)
2. python環境
開始:
1.設備連接
android手機打開開發者模式,USB連接電腦,允許USB除錯,
命令列輸入adb devices查看設備,AWMCUT1224008813為設備序列號待會要用
>adb devices
List of devices attached
AWMCUT1224008813 device
2.安裝UiAutomator2
確保python環境沒有問題,我這里使用的python3
命令列運行pip3 install -U uiautomator2 安裝UiAutomator2
3.安裝httprpc服務
運行python -m uiautomator2 init安裝包含httprpc服務的apk到手機
上述初始化命令會自動安裝本庫所需要的設備端程式:uiautomator-server、atx-agent、openstf/minicap、openstf/minitouch,并且在被測手機終端上會安裝一個名為ATX的代理程式
4.安裝weditor
運行pip3 install --pre -U weditor安裝weditor在線元素查看器,weditor --help查看是否安裝成功
5. 使用weditor查看界面元素
命令列執行 weditor 會自動打開瀏覽器(http://localhost:17310/),輸入設備的ip或者序列號,點擊Connect,打開實時開關,

此時打開app,可以在右側Hierarchy查看界面元素樹

6.撰寫腳本獲取評論串列文本內容
d = u2.connect('AWMCUT1224008813') 對應連接設備的序列號,
#coding=utf8
import uiautomator2 as u2
import time
import logging
import re
import json
from string import Template
d = u2.connect('AWMCUT1224008813')
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("當前是打開狀態??")
print("size:", d.xpath('//*[@resource-id="com.ss.android.ugc.aweme:id/fvw"]/android.widget.RelativeLayout').all())
for index,elem in enumerate(d.xpath('//*[@resource-id="com.ss.android.ugc.aweme:id/fvw"]/android.widget.RelativeLayout').all()):
print("%s" %(index+1))
i = index + 1
s = f"//android.widget.RelativeLayout[{i}]/android.widget.TextView"
print(s)
print("item:", d.xpath(s).text)
else:
logger.info("未找到指定文本??")
else:
print('app打開錯誤')
while True:
print('------獲取當前螢屏評論資料------')
run_app()
time.sleep(10)
部分log如下:
分類: 美食探店
1
//android.widget.RelativeLayout[1]/android.widget.TextView
item: 說點什么...
2
//android.widget.RelativeLayout[2]/android.widget.TextView
item: $ 楠楠楠:店鋪
3
//android.widget.RelativeLayout[3]/android.widget.TextView
item: $ 鎖鎖美:4號代金券限菜品嗎使用嗎?
4
//android.widget.RelativeLayout[4]/android.widget.TextView
item: $ 小熙:怎么適應
5
//android.widget.RelativeLayout[5]/android.widget.TextView
item: $ 小熙:怎么使用
6
//android.widget.RelativeLayout[6]/android.widget.TextView
item: 耶啵啵:那為什么顯示生菜一份 兩人需要再付一份?
7
//android.widget.RelativeLayout[7]/android.widget.TextView
item: Joker男士理發館Jimmy 來了
[Finished 9.701s]
這段腳本執行后會根據包名自動打開抖音,在直播頁面通過d.xpath('//*[@resource-id="com.ss.android.ugc.aweme:id/fvw"]')獲取評論串列的recyclerview,再通過遍歷recyclerview下的RelativeLayout列印出RelativeLayout下的TextView中內容,當然也可以直接遍歷TextView的id(text)來進行獲取,注意:不同設備的ViewGroup的id也就是TextView的父view的id可能會不同,
對串列元素的遍歷是從1開始的,
另外,此時僅獲取到當前螢屏上的資料,這里加個定時器(每10秒)不斷的進行獲取并保存,再對資料去重,
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/301021.html
標籤:其他
上一篇:想做測驗都需要哪些知識儲備呢?
