解决WhatsApp自动化脚本Selenium NoSuchElementException及弃用警告问题
问题修复方案
一、DeprecationWarning弃用警告修复
原因
Selenium 4.0及以上版本已完全废弃find_element_by_*系列方法,统一要求使用find_element(By.定位方式, 定位值)的语法调用,你代码里的find_element_by_xpath属于已废弃的写法。同时Chrome驱动加载的executable_path参数也已同步废弃。
修复方法
所有find_element_by_xpath替换为标准写法,比如原来的browser.find_element_by_xpath(group_xpath)改为browser.find_element(By.XPATH, group_xpath);驱动加载改用Service类实现。
二、NoSuchElementException找不到输入框元素修复
原因
- 点击群组后硬等待1秒稳定性差,网络或设备卡顿情况下输入框还没渲染完成就执行定位操作
- 旧版WhatsApp网页版的输入框
data-tab属性值为1,新版页面结构更新后该属性值已经变动,原XPath完全失效
修复方法
- 对输入框、群组标题的定位都增加显式等待,确保元素加载完成后再操作
- 更换更稳定的输入框XPath,使用
//footer//div[@contenteditable="true"]定位,不受data-tab属性值变动影响 - 修正原代码中文件读取的缩进错误,避免语法报错
完整修复后的代码
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.webdriver.common.keys import Keys from selenium.webdriver.chrome.service import Service import pyperclip import time import sys from config import CHROME_PROFILE_PATH # 修正Chrome驱动加载写法,适配Selenium4 browser = webdriver.Chrome( service=Service('C:/Users/Admin/chromedriver/chromedriver.exe') ) browser.maximize_window() browser.get('https://web.whatsapp.com/') # 修正文件读取缩进错误 with open('C:/flask/new/Login-Page-With-Flask-HTML/src/groups.txt', 'r', encoding='utf8') as f: groups = [group.strip() for group in f.readlines()] with open('C:/flask/new/Login-Page-With-Flask-HTML/src/msg.txt', 'r', encoding='utf8') as f: msg = f.read() for group in groups: search_xpath = '//div[@contenteditable="true"][@data-tab="3"]' search_box = WebDriverWait(browser, 500).until( EC.presence_of_element_located((By.XPATH, search_xpath)) ) search_box.clear() time.sleep(1) pyperclip.copy(group) search_box.send_keys(Keys.SHIFT, Keys.INSERT) time.sleep(2) # 修正群组定位写法,加显式等待、替换废弃方法 group_xpath = f'//span[@title="{group}"]' group_title = WebDriverWait(browser, 10).until( EC.presence_of_element_located((By.XPATH, group_xpath)) ) group_title.click() time.sleep(1) # 修正输入框定位,换稳定XPath、加显式等待、替换废弃方法 input_xpath = '//footer//div[@contenteditable="true"]' input_box = WebDriverWait(browser, 10).until( EC.presence_of_element_located((By.XPATH, input_xpath)) ) pyperclip.copy(msg) input_box.send_keys(Keys.SHIFT, Keys.INSERT) input_box.send_keys(Keys.ENTER) time.sleep(2)
内容的提问来源于stack exchange,提问作者PRAJAKTA BARDE
相关产品推荐
相关产品推荐

