強大!用 60 行代碼自動搶微信紅包


春節來到,紅包們大機率在微信各大羣中肆虐,你們是否都同樣不搶到紅包們內心就感受錯過了一個億,可總會被這事那事耽誤而遺憾錯過,下面用 Python 寫一個自動搶紅包代碼
android

啓動入口

啓動程序的配置和公衆號文章《用 Python + Appium 的方式自動化清理微信殭屍好友》的配置同樣web

from appium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from appium.webdriver.common.touch_action import TouchAction
from selenium.webdriver.support import expected_conditions as EC

desired_capabilities = {
    'platformName''Android'# 操做系統
    'deviceName''2a254a02'# 設備 ID
    'platformVersion''10.0.10'# 設備版本號,在手機設置中查看
    'appPackage''com.tencent.mm'# app 包名
    'appActivity''com.tencent.mm.ui.LauncherUI'# app 啓動時主 Activity
    'noReset'True # 是否保留 session 信息 避免從新登陸
}

driver = webdriver.Remote('http://localhost:4723/wd/hub', desired_capabilities)
# 設置等待超時時間
wait = WebDriverWait(driver, 60)

點擊進入聊天窗口

微信在通常狀況下最新的聊天記錄將被放在第一個,因此只須要打開第一個聊天窗口檢查有沒有紅包就能夠了,用 id 爲 com.tencent.mm:id/e3x 能夠找到全部的聊天信息,咱們取第一個聊天羣的索引微信

# 進入第一個聊天框
red_packet_group = driver.find_elements_by_id('com.tencent.mm:id/e3x')[0]
red_packet_group.click()

找到紅包

進入聊天羣后,紅包圖片檢查是否存在紅包,它的 id 爲 com.tencent.mm:id/r2session

 # 檢查紅包
reds = driver.find_elements_by_id('com.tencent.mm:id/r2')
if len(reds) == 0:
    driver.keyevent(4)

搶紅包

點擊紅包後會出現如下 3 種狀況app

  1. 紅包已經被本身領取了
  2. 紅包手慢了沒搶到
  3. 紅包未領取

前兩種狀況紅包已經失效了,最後一種纔是能夠打開的紅包編輯器

紅包已經失效了

在上面代碼中都是用 id 檢查元素是否存在,這裏使用查找文字已存入零錢手慢了判斷紅包是否已經失效svg

# 判斷元素是否存在
def is_element_exist_by_xpath(driver, text):
    try:
        driver.find_element_by_xpath(text)
    except Exception as e:
        return False
    else:
        return True


# 領取了
is_open = is_element_exist_by_xpath(driver, '//android.widget.TextView[contains(@text, "已存入零錢")]')
# 沒搶到
is_grabbed = is_element_exist_by_xpath(driver, '//android.widget.TextView[contains(@text, "手慢了")]')

if is_open or is_grabbed:
    driver.keyevent(4)

打開紅包

打開紅包比較簡單,只須要找到  字的 id學習

wait.until(EC.element_to_be_clickable((By.ID, "com.tencent.mm:id/den"))).click()
wait.until(EC.element_to_be_clickable((By.ID, "com.tencent.mm:id/dm"))).click()

刪除紅包

最後咱們將紅包刪除,防止紅包被重複打開。當長按紅包時,微信紅包會出現刪除按鈕測試

TouchAction(driver).long_press(red).perform()
wait.until(EC.element_to_be_clickable((By.ID, "com.tencent.mm:id/gam"))).click()
wait.until(EC.element_to_be_clickable((By.ID, "com.tencent.mm:id/doz"))).click()

總結

這是學習並使用 Appium 的第三篇文章,Appium 能夠將手機操做自動化,你們學廢了嗎?flex


end


本文分享自微信公衆號 - 測試開發社區(TestDevHome)。
若有侵權,請聯繫 support@oschina.cn 刪除。
本文參與「OSC源創計劃」,歡迎正在閱讀的你也加入,一塊兒分享。

相關文章
相關標籤/搜索