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

Selenium Python脚本异常:WhatsApp Web扫码无响应及设备连接错误

WhatsApp Web Selenium脚本异常问题解决

问题描述

使用以下Python Selenium脚本向指定号码发送文件和消息时,出现错误提示Failed to read descriptor from node connection: A device attached to the system is not functioning,扫码登录后脚本无后续操作:

from selenium import webdriver
from selenium.common.exceptions import NoSuchElementException
import time
import os

# Replace with the path to your chromedriver executable
chromedriver_path = os.path.join(os.getcwd(), 'chromedriver_win32', 'chromedriver.exe')

# Replace with the path to the files you want to send
files_to_send = [os.path.join(os.getcwd(), 'files', 'In action presentation.pdf'),
os.path.join(os.getcwd(), 'files', 'WhatsApp Audio 2023-03-08 at 12.15.51 AM.ogg')]

# Replace with your message text
message = "Hello, this is a test message."

# List of phone numbers
phone_numbers = ['+1234567890']

# Initialize the Chrome webdriver
driver = webdriver.Chrome(chromedriver_path)

# Open WhatsApp Web
driver.get('https://web.whatsapp.com/')

# Wait for the user to scan the QR code
input('Scan the QR code and press Enter to continue...')

# Loop through the list of phone numbers
for phone_number in phone_numbers:
    # Navigate to the chat with the phone number
    driver.get(f'https://web.whatsapp.com/send?phone={phone_number}')

    try:
        # Wait for the chat window to load
        chat_window = driver.find_element_by_xpath('//div[@class="_3uMse"]')
        time.sleep(5)

        # Click on the attachment button
        attachment_button = driver.find_element_by_xpath('//div[@title="Attach"]')
        attachment_button.click()

        # Click on the "Document" option
        document_button = driver.find_element_by_xpath('//input[@accept="*"]')
        document_button.send_keys('\n'.join(files_to_send))

        # Wait for the files to upload
        time.sleep(10)

        # Type the message text
        message_box = driver.find_element_by_xpath('//div[contains(@class, "input")]')
        message_box.send_keys(message)

        # Send the message
        send_button = driver.find_element_by_xpath('//span[@data-icon="send"]')
        send_button.click()
    except NoSuchElementException:
        print(f'Unable to send message to {phone_number}. Chat window not found.')

# Close the webdriver
driver.quit()

解决步骤

1. 修复ChromeDriver兼容性

该错误多数源于Chrome浏览器与ChromeDriver版本不匹配,建议用webdriver-manager自动管理驱动,避免手动路径配置错误:

  • 安装依赖:pip install webdriver-manager

2. 替换过时的Selenium API

Selenium 4.x已弃用find_element_by_xpath这类旧方法,需改用find_element(By.XPATH, 'xxx'),同时导入By模块。

3. 替换固定sleep为显式等待

固定等待时间不可靠,改用WebDriverWait等待元素加载完成,避免因页面加载慢导致元素查找失败。

4. 修正文件上传路径格式

Windows系统下,多文件上传需用**分号(;)**分隔路径,而非换行符。

5. 更新WhatsApp Web元素定位

WhatsApp Web的DOM元素属性可能已更新,需调整XPath确保能正确定位元素。

修改后的完整脚本

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
import time
import os
from webdriver_manager.chrome import ChromeDriverManager

# 自动获取匹配版本的ChromeDriver
driver = webdriver.Chrome(ChromeDriverManager().install())

# 文件路径配置
files_to_send = [
    os.path.join(os.getcwd(), 'files', 'In action presentation.pdf'),
    os.path.join(os.getcwd(), 'files', 'WhatsApp Audio 2023-03-08 at 12.15.51 AM.ogg')
]
message = "Hello, this is a test message."
phone_numbers = ['+1234567890']

driver.get('https://web.whatsapp.com/')
input('Scan the QR code and press Enter to continue...')

wait = WebDriverWait(driver, 15)

for phone_number in phone_numbers:
    driver.get(f'https://web.whatsapp.com/send?phone={phone_number}')
    try:
        # 等待聊天窗口加载完成
        wait.until(EC.presence_of_element_located((By.XPATH, '//div[@class="_3uMse"]')))
        time.sleep(2)  # 短等待确保界面稳定

        # 点击附件按钮
        attachment_btn = wait.until(EC.element_to_be_clickable((By.XPATH, '//div[@title="Attach"]')))
        attachment_btn.click()

        # 上传文件(Windows用分号分隔多文件路径)
        file_input = wait.until(EC.presence_of_element_located((By.XPATH, '//input[@accept="*"]')))
        file_input.send_keys(';'.join(files_to_send))

        # 等待文件上传完成(根据文件大小调整等待逻辑)
        wait.until(EC.invisibility_of_element_located((By.XPATH, '//div[@class="_26f9u"]')))
        time.sleep(3)

        # 输入消息内容
        msg_box = wait.until(EC.element_to_be_clickable((By.XPATH, '//div[@contenteditable="true"][@data-tab="1"]')))
        msg_box.send_keys(message)

        # 发送消息
        send_btn = wait.until(EC.element_to_be_clickable((By.XPATH, '//span[@data-icon="send"]')))
        send_btn.click()

        time.sleep(5)  # 等待消息发送完成
    except (NoSuchElementException, TimeoutException):
        print(f'Failed to send to {phone_number}: Element not found or timeout.')

driver.quit()

额外注意事项

  • 确保Chrome浏览器为最新版本,webdriver-manager会自动匹配对应驱动
  • 若仍出现设备相关错误,可关闭Chrome硬件加速:设置→系统→关闭「使用硬件加速模式(如果可用)」后重启浏览器
  • WhatsApp Web有反自动化机制,避免短时间批量发送大量消息,建议添加合理间隔时间

内容的提问来源于stack exchange,提问作者Ahmed Mohamed

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.28 14:47:47