如何实现WhatsApp Web定时群发消息且无需重复扫码?
WhatsApp Web 定时群发脚本优化方案(每小时重复发送)
需求说明
现有基于Selenium 4.0的WhatsApp Web群发脚本仅能完成单次群发,需优化为每小时向所有目标群组发送一次消息,且全程保持浏览器会话(无需重复扫码登录)。
修改后完整代码
import pandas as pd from time import sleep, time from selenium import webdriver from selenium.webdriver.common.by import By from selenium.webdriver.common.keys import Keys from selenium.webdriver import ChromeOptions, Chrome from selenium.webdriver.chrome.service import Service from webdriver_manager.chrome import ChromeDriverManager # 配置浏览器选项,保持会话不关闭 opts = ChromeOptions() opts.add_experimental_option('detach', True) opts.add_experimental_option('excludeSwitches', ['enable-logging']) # 初始化浏览器驱动 servico = Service(ChromeDriverManager().install()) driver = webdriver.Chrome(service=servico, options=opts) # 打开WhatsApp Web,等待扫码登录 driver.get('https://web.whatsapp.com/') driver.implicitly_wait(60) # 最长等待60秒完成登录 # 读取Excel中的群组和消息配置 col_nome = 'Nome' col_mensagem = 'Mensagem' infor_excel = pd.read_excel('C:\\Users\\felip\\OneDrive\\Área de Trabalho\\Web\\Mensagens.xlsx') lista_msg_excel = infor_excel[[col_nome, col_mensagem]] def buscar_contato(contato_nome): # 定位搜索框并搜索群组 campo_pesquisa = driver.find_element(By.CSS_SELECTOR, '.selectable-text') sleep(2) campo_pesquisa.click() # 清空搜索框避免残留内容 campo_pesquisa.send_keys(Keys.CONTROL + 'a') campo_pesquisa.send_keys(Keys.BACKSPACE) sleep(1) campo_pesquisa.send_keys(contato_nome) sleep(2) campo_pesquisa.send_keys(Keys.ENTER) def enviar_mensagem(mensagem_texto): # 定位消息输入框并发送消息 campo_mensagem = driver.find_elements(By.CSS_SELECTOR, 'p[class="selectable-text copyable-text"]') sleep(2) campo_mensagem[0].click() sleep(1) campo_mensagem[0].send_keys(mensagem_texto) sleep(1) campo_mensagem[0].send_keys(Keys.ENTER) # 无限循环实现每小时群发 while True: print(f"开始新一轮群发,时间:{time()}") for index, row in lista_msg_excel.iterrows(): try: buscar_contato(str(row[col_nome])) enviar_mensagem(str(row[col_mensagem])) print(f"已发送至群组:{row[col_nome]}") except Exception as e: print(f"发送至群组 {row[col_nome]} 失败,错误:{str(e)}") # 发送失败后回到主界面,避免影响下一个群组 driver.find_element(By.CSS_SELECTOR, 'span[data-icon="back"]').click() sleep(2) # 完成一轮群发后,暂停3600秒(1小时) print("本轮群发完成,等待1小时后继续...") sleep(3600)
关键优化点
- 修复原脚本逻辑漏洞:原函数未使用传入的参数,直接依赖外部
row变量,修改后函数通过参数接收目标群组和消息,逻辑更严谨 - 添加定时循环:用
while True实现无限重复,每轮群发完成后调用sleep(3600)暂停1小时 - 搜索框清空处理:每次搜索前清空输入框,避免残留内容导致搜索错误
- 异常处理:添加try-except捕获发送失败的情况,失败后自动返回主界面,不影响后续群组发送
- 维持会话:保留
detach选项,确保浏览器在脚本运行期间保持打开,维持WhatsApp登录状态
内容的提问来源于stack exchange,提问作者Felipe
相关产品推荐
相关产品推荐

