Python+Selenium开发WhatsApp机器人遇Chromedriver权限错误求助
先帮你拆解遇到的两个问题:一个是API过时的警告,另一个是权限被拒绝的致命错误,咱们一步步来解决。
一、先处理DeprecationWarning警告
这个警告是小问题,Selenium更新后chrome_options参数已经被废弃,官方推荐用options替代。如果你的代码里用到了chrome_options,直接改成options就行,比如:
# 旧写法(已过时) chrome_options = webdriver.ChromeOptions() driver = webdriver.Chrome(executable_path='xxx', chrome_options=chrome_options) # 新写法(正确) options = webdriver.ChromeOptions() driver = webdriver.Chrome(executable_path='xxx', options=options)
如果是Selenium 4.x版本,更推荐用Service类管理驱动路径,写法会更规范,后面我会给出完整示例。
二、解决PermissionError: [WinError 5] 权限被拒绝
你已经尝试了管理员运行和修改文件夹权限但没解决,大概率是以下几个原因:
1. ChromeDriver与Chrome浏览器版本不匹配
这是最容易踩的坑!ChromeDriver版本必须和你电脑上的Chrome浏览器大版本完全一致(比如Chrome是118.xx,ChromeDriver也要118.xx)。你可以:
- 打开Chrome,在地址栏输入
chrome://version/查看浏览器版本 - 下载对应版本的ChromeDriver(注意选对应系统的安装包)
- 替换掉当前使用的旧驱动
2. 不要把ChromeDriver放在Python的Scripts文件夹
Python安装目录(尤其是Program Files下的)权限管控严格,容易触发权限冲突。建议把ChromeDriver放在普通用户文件夹里,比如桌面的SeleniumTools文件夹,再在代码里指定这个路径。
3. 杀毒软件/Windows Defender拦截了ChromeDriver
很多杀毒软件会把ChromeDriver这类自动化工具误判为恶意程序,直接拦截运行。你可以:
- 暂时关闭杀毒软件测试是否能正常运行
- 如果没问题,把ChromeDriver路径添加到杀毒软件的信任列表
4. 指定Chrome浏览器的安装路径(可选)
如果Chrome默认安装在Program Files目录,权限较高,你可以通过options指定Chrome可执行文件路径,避免权限冲突:
options = webdriver.ChromeOptions() # 替换成你Chrome的实际安装路径 options.binary_location = r'C:\Program Files\Google\Chrome\Application\chrome.exe'
三、修正后的完整代码
结合上面的解决方案,整理了一份可用的代码(基于Selenium 4.x):
from selenium import webdriver from selenium.webdriver.chrome.service import Service from selenium.webdriver.common.by import By # 指定ChromeDriver路径(建议放在用户自己的文件夹) service = Service(executable_path=r'C:\Users\Jo\Desktop\SeleniumTools\chromedriver.exe') options = webdriver.ChromeOptions() # 可选:指定Chrome浏览器二进制文件路径 # options.binary_location = r'C:\Program Files\Google\Chrome\Application\chrome.exe' # 初始化驱动 driver = webdriver.Chrome(service=service, options=options) driver.get('http://web.whatsapp.com') name = input('Enter the name of user or group : ') msg = input('Enter the message : ') count = int(input('Enter the count : ')) # 扫码后继续 input('Enter anything after scanning QR code') # 注意:Selenium 4.x已废弃旧的定位方法,推荐用By类 user = driver.find_element(By.XPATH, '//span[@title = "{}"]'.format(name)) user.click() msg_box = driver.find_element(By.CLASS_NAME, 'input-container') for i in range(count): msg_box.send_keys(msg) driver.find_element(By.CLASS_NAME, 'compose-btn-send').click()
补充一点:Selenium 4.x已经废弃了find_element_by_xpath、find_element_by_class_name这类旧方法,官方推荐用find_element(By.XXX, '定位符')的写法,我已经在代码里帮你替换了,避免后续出现新警告。
内容的提问来源于stack exchange,提问作者PyroByte

