前言
利用利用Python 自動化來獲取某類商品中最好賣的商品以供參考。廢話不多說。
讓我們愉快地開始吧~
開發工具
Python版本: 3.6.4
相關模塊:
pyecharts模塊;
以及一些Python自帶的模塊。
環境搭建
安裝Python並添加到環境變量,pip安裝需要的相關模塊即可。
準備工作
1、配置好 Android ADB 開發環境
2、Python 虛擬環境內安裝 pocoui 依賴庫
# pocoui\
pip3 install pocoui
# 數據可視化圖表
pip3 install pyecharts -U
步驟
我們分 7 個步驟來實現這個功能,分別是:打開目標應用客戶端、檢索關鍵字到商品列表界面、計算最佳滑動距離、篩選商品、獲取商品鏈接地址、寫入文件排序並統計商品、配置參數。
第 1 步,使用 pocoui 自動化打開目標應用。
def __pre(self):
"""
準備工作
:return:
"""
home()
stop_app(package_name)
start_my_app(package_name, activity)
# 等待到達桌面
self.poco(text='閒魚').wait_for_appearance()
self.poco(text='魚塘').wait_for_appearance()
self.poco(text='消息').wait_for_appearance()
self.poco(text='我的').wait_for_appearance()
print('進入閒魚主界面')
進入到閒魚首頁之後,應用端會拿到剪切板的數據,當存在特定規律的口令的時,會立馬彈出一個對話框, 因此需要模擬關閉對話框的操作。
# 如果指定時間內內有淘口令,就關閉\
for i in range(10, -1, -1):\
close_element = self.poco('com.taobao.idlefish:id/ivClose')\
if close_element.exists():\
close_element.click()\
break\
time.sleep(1)
第 2 步,檢索關鍵字到商品列表界面
通過要檢索的關鍵字,模擬輸入到輸入框內,然後點擊搜索按鈕,一直等待搜過列表出現爲止。
另外,爲了更加方便地處理數據,商品列表切換到列表模式,即一行只顯示一個商品。
def __input_key_word(self):
"""
輸入關鍵字
:return:
"""
# 進入搜索界面
perform_click(self.poco('com.taobao.idlefish:id/bar_tx'))
# 搜索框內輸入文本
self.poco('com.taobao.idlefish:id/search_term').set_text(self.good_msg)
# 點擊搜索按鈕
while True:
# 等待檢索結果列表出現
if not self.poco('com.taobao.idlefish:id/list_recyclerview').exists():
perform_click(self.poco('com.taobao.idlefish:id/search_button', text='搜索'))
else:
break
# 等待商品列表完全出現
self.poco('com.taobao.idlefish:id/list_recyclerview').wait_for_appearance()
# 切換到列表
perform_click(self.poco('com.taobao.idlefish:id/switch_search'))
第 3 步,計算最佳滑動距離。
爲了保證爬取數據的高效性,獲取計算出每次滑動的最佳距離。
首先先拿到當前界面的 UI 控件樹,然後通過控件的屬性 ID 拿到商品的座標,進而得到每一項商品的高度。
最後,通過觀察屏幕中出現商品的數目得到最佳滑動距離。
def __get_good_swipe_distance(self):
"""
獲取每次滑動,最合適的距離
:return:
"""
element = Element()
# 保存當前的UI樹到本地
element.get_current_ui_tree()
# 第一個商品Item的座標
position_item = element.find_elment_position_by_id_and_index("com.taobao.idlefish:id/card_root",
"1")
# 商品的高度
item_height = position_item[1][1] - position_item[0][1]
# 通過觀察,當前屏幕有3件商品
return item_height * 3
第 4 步,篩選商品。
上面的步驟拿到最佳的滑動距離,不停的滑動頁面遍歷列表元素的子 Item。
需要注意的是,爲了避免滑動慣性導致的誤差,每一次的滑動時長最好設置爲 2s 以上。
通過商品 Item 篩選出想要數目大於預設數字的商品。
# 多少人想要
want_element_parent = item.offspring('com.taobao.idlefish:id/search_item_flowlayout')
if want_element_parent.exists():
# 想要數/已付款數目
want_element = want_element_parent.children()[0]
want_content = want_element.get_text()
# 過濾掉【已付款】等其他商品,只保留個人發佈商品
if '人想要' not in want_content:
continue
# 拿到商品想要的具體數目,代表商品熱度
want_num = get_num(want_content)
if int(want_num) < self.num_assign:
# print('不達標,過濾掉')
pass
else:
# 商品想要數達標,加入統計
第 5 步,獲取商品鏈接地址
對於上一步滿足條件的商品,點擊商品 Item 進入到商品詳情頁面。
接着點擊右上角的分享按鈕,會立即彈出分享對話框。
然後點擊口令控件,會提示口令複製到系統剪切板成功。
# 點擊更多
while True:
if self.poco('com.taobao.idlefish:id/ftShareName').exists():
break
print('點擊更多~')
perform_click(self.poco(text='更多'))
# 點擊複製淘口令
perform_click(self.poco('com.taobao.idlefish:id/ftShareName', text='淘口令'))
# 拿到口令碼
taobao_code_element = self.poco('com.taobao.idlefish:id/tvWarnDetail')
taobao_code = taobao_code_element.get_text()
第 6 步,寫入商品、排序並統計數據
將上面獲取到的商品標題、想要數、分享地址寫入到 CSV 文件中。
然後讀取數據文件,通過對錶格中的第二列進行反向排序, 使商品按照想要數進行降序排列。
def __sort_result(self):
"""
對爬取的結果進行排序
:return:
"""
reader = csv.reader(open(self.file_path), delimiter=",")
# 頭部標題
head_title = next(reader)
# 按照第二列進行逆序排列
sortedlist = sorted(reader, key=lambda x: (int(x[1])), reverse=True)
# 寫入頭部數據
write_to_csv(self.file_path, [(head_title[0], head_title[1], head_title[2])], False)
for value in sortedlist:
write_to_csv(self.file_path, [(value[0], value[1], value[2])], False)
return sortedlist
最後拿到前 10 項數據,利用 pyecharts 生成統計圖表。
def draw_image(self, sortedlist):
"""
畫圖
:param sortedlist:
:return:
"""
# 標題列表
titles = []
# 銷量
sales_num = []
# 拿到爬取結果的標題、銷量兩個列表
with open(self.file_path, 'r') as csvfile:
# 讀取文件
reader = csv.DictReader(csvfile)
# 加入列表中
for row in reader:
titles.append(row['title'])
sales_num.append(row['num'])
# 數目限制
if len(titles) > self.num:
titles = titles[:self.num]
sales_num = sales_num[:self.num]
# 畫圖
bar = (
Bar()
.add_xaxis(titles)
.add_yaxis("哪些好賣", sales_num)
.set_global_opts(title_opts=opts.TitleOpts(title="我要賣貨"))
)
bar.render('%s.html' % self.good_msg)
第 7 步,配置參數
編寫 yaml 文件,指定要爬取商品的關鍵字、爬取時間、想要數考覈指標數、篩選商品數目。
goods:
# 搜索商品1,包含搜索關鍵字、爬取時間
good1:
key_word: '資料' # 搜索關鍵字
key_num: 100 # 篩選【想要數】的臨界點
num: 10 # 只篩選爆款
time: 600 # 爬取時間(秒)
效果展示
提前配置好商品關鍵字、爬取時間等參數,即可以爬取到符合要求的、最好賣的商品數據,最終以圖表的方式展示出來。