Python封装Chrome WebDriver为函数时出现WinError 5权限拒绝问题
问题场景
直接执行Chrome WebDriver代码可正常运行,但将逻辑封装到main1函数中执行时,抛出权限拒绝错误,且当前用户已拥有管理员权限。
相关代码
url=['https://www.youtube.com/results?search_query=free+code+camp'] def main1(): try: driver = webdriver.Chrome('chromedriver.exe') driver.get(url[0]) driver.implicitly_wait(10) except Exception as e: print(e) main1()
报错信息
Traceback (most recent call last):
File "C:\Users\asus\anaconda3\envs\Jinja2_sample1\lib\subprocess.py", line 788, in del
self._internal_poll(_deadstate=_maxsize)
File "C:\Users\asus\anaconda3\envs\Jinja2_sample1\lib\subprocess.py", line 1055, in _internal_poll
if _WaitForSingleObject(self._handle, 0) == _WAIT_OBJECT_0:
PermissionError: [WinError 5] 访问被拒绝
可行解决方案
指定chromedriver绝对路径:直接写
chromedriver.exe可能导致函数执行时路径解析异常,替换为绝对路径,示例:driver = webdriver.Chrome(r'C:\your_local_path\chromedriver.exe')清理Chrome残留进程:打开任务管理器,结束所有
chrome.exe和chromedriver.exe进程,残留进程可能占用资源引发权限冲突。以管理员身份运行Python环境:右键点击IDE或命令提示符,选择「以管理员身份运行」再执行脚本,确保Python进程获取到管理员权限。
修改chromedriver文件权限:右键
chromedriver.exe→ 属性 → 安全,为当前用户分配「完全控制」权限,避免系统拦截执行。添加ChromeOptions启动参数:启用无沙箱模式绕过部分系统限制,示例:
from selenium.webdriver.chrome.options import Options def main1(): try: chrome_options = Options() chrome_options.add_argument('--no-sandbox') chrome_options.add_argument('--disable-dev-shm-usage') driver = webdriver.Chrome('chromedriver.exe', options=chrome_options) driver.get(url[0]) driver.implicitly_wait(10) except Exception as e: print(e)检查杀毒软件拦截:部分杀毒软件会误判chromedriver为恶意程序,暂时关闭或将其添加至信任列表后重试。
内容的提问来源于stack exchange,提问作者arpit

