一聚教程网:一个值得你收藏的教程网站

最新下载

热门教程

用60行代码实现Python自动抢微信红包代码

时间:2021-02-04 编辑:袖梨 来源:一聚教程网

本篇文章小编给大家分享一下用60行代码实现Python自动抢微信红包代码,文章代码介绍的很详细,小编觉得挺不错的,现在分享给大家供大家参考,有需要的小伙伴们可以来看看。

启动入口

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/r2

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

抢红包

点击红包后会出现以下 3 种情况

红包已经被自己领取了

红包手慢了没抢到

红包未领取

前两种情况红包已经失效了,最后一种才是可以打开的红包

红包已经失效了

在上面代码中都是用 id 检查元素是否存在,这里使用查找文字已存入零钱和手慢了判断红包是否已经失效

# 判断元素是否存在
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()

热门栏目