You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

基于Selenium与Python的WhatsApp机器人:如何跳过未注册WhatsApp的号码

解决WhatsApp机器人跳过未注册号码的问题

我来帮你搞定这个需求!当遇到未注册WhatsApp的号码时,WhatsApp Web会显示对应的错误提示(比如“该号码未注册WhatsApp”或对应语言的提示),我们可以通过检测这些提示元素来判断是否跳过当前号码。

实现思路

  • 进入发送链接后,先检测页面是否存在无效号码的提示元素
  • 如果检测到提示,直接跳过当前号码,继续处理下一个
  • 如果没有提示,再执行点击发送按钮的操作

修改后的代码

from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.common.exceptions import NoSuchElementException, TimeoutException
from webdriver_manager.chrome import ChromeDriverManager
from urllib.parse import quote
import time
from openpyxl import load_workbook  # 修正原代码的导入路径

def readContacts(fileName):
    delay = 30
    f = open("message.txt", encoding='utf-8')
    ads = f.read()
    f.close()
    ads = quote(ads)
    lst = []
    file = load_workbook(fileName)
    sheet = file.active
    firstCol = sheet['A']
    secondCol = sheet['B']
    driver = webdriver.Chrome(ChromeDriverManager().install())
    driver.get('https://web.whatsapp.com')
    time.sleep(10)  # 延长扫码登录等待时间,确保登录完成
    
    for cell in range(len(firstCol)):
        contact = str(firstCol[cell].value).strip()  # 清理号码前后空格,避免格式错误
        message = str(secondCol[cell].value)
        link = f"https://web.whatsapp.com/send?phone={contact}&text={message} عزیز %0A {ads}"
        driver.get(link)
        print(f"Processing contact: {contact}")
        
        try:
            # 检测无效号码提示(这里以波斯语提示为例,可根据实际页面文本修改)
            error_element = WebDriverWait(driver, 10).until(
                EC.presence_of_element_located((By.XPATH, "//div[contains(text(), 'شماره نامعتبر است')]"))
            )
            print(f"Contact {contact} is not registered on WhatsApp, skipping...")
            continue
        except TimeoutException:
            # 未检测到错误提示,继续执行发送逻辑
            pass
        
        try:
            click_btn = WebDriverWait(driver, delay).until(EC.element_to_be_clickable((By.CLASS_NAME , '_4sWnG')))
            click_btn.click()
            time.sleep(5)
            print(f"Message sent successfully to {contact}")
        except (NoSuchElementException, TimeoutException):
            print(f"Failed to send message to {contact}")
    
    driver.quit()

targets = readContacts("./contact.xlsx")

关键说明

  • 错误元素定位:我用了波斯语提示文本'شماره نامعتبر است'(意为“无效号码”),你可以手动打开WhatsApp Web测试一个未注册号码,复制页面上的提示文本替换进去;也可以用元素类名定位,比如错误提示容器的专属类。
  • 登录等待优化:原代码的time.sleep(1)太短,扫码登录需要时间,延长至10秒更稳妥。
  • 号码格式处理:增加strip()清理号码前后空格,避免因格式问题导致的无效请求。
  • 异常处理优化:用TimeoutException替代NoSuchElementException,更准确判断元素是否存在。

这样修改后,机器人遇到未注册的号码就会自动跳过,继续处理下一个联系人啦!

内容的提问来源于stack exchange,提问作者Pedram Gholizadeh

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.28 14:18:13