macOS Sonoma下Python+Selenium打开Chromium后自动退出问题求助
解决Selenium打开Chromium后立即退出的问题
核心问题分析
你的代码存在几个关键问题导致浏览器启动后立刻退出:
Service实例未指定chromedriver的具体路径,Selenium无法正确定位驱动程序- 代码执行到
driver.get后无阻塞逻辑,程序直接结束,浏览器进程随之被销毁 - 可能存在Chromium与chromedriver版本不匹配的情况
具体解决方案
1. 正确指定chromedriver路径
修改Service初始化代码,传入chromedriver的绝对路径:
service = Service(executable_path='/Users/admin/Downloads/chromedriver_mac_arm64/chromedriver')
2. 添加阻塞逻辑防止程序直接结束
在driver.get之后添加延迟或交互逻辑,让浏览器保持打开状态:
driver.get('https://www.google.com') # 让浏览器保持打开10秒,可根据需求调整时长 time.sleep(10) # 程序结束前手动关闭驱动(可选,若需手动关闭浏览器可注释此行) driver.quit()
3. 检查Chromium与chromedriver版本匹配
- 打开Chromium,在地址栏输入
chrome://version查看版本号 - 确保下载的chromedriver版本与Chromium主版本完全一致(例如Chromium为128.x,chromedriver也需为128.x)
4. 处理macOS权限问题
若仍报错,可能是chromedriver无执行权限,在终端执行:
chmod +x /Users/admin/Downloads/chromedriver_mac_arm64/chromedriver
另外,macOS可能阻止未签名驱动,需在「系统设置-隐私与安全性」中允许chromedriver运行。
修改后的完整代码
import requests from bs4 import BeautifulSoup from selenium import webdriver import time from selenium.webdriver.chrome.service import Service # 指定chromedriver的绝对路径 service = Service(executable_path='/Users/admin/Downloads/chromedriver_mac_arm64/chromedriver') requests.get("http://www.google.com") def web_driver(): options = webdriver.ChromeOptions() options.binary_location = '/Applications/Chromium.app/Contents/MacOS/Chromium' options.add_argument("--verbose") options.add_argument('--no-sandbox') # 如需可视化浏览器窗口,可注释掉--headless参数 # options.add_argument('--headless') options.add_argument('--disable-gpu') options.add_argument("--window-size=1920, 1200") driver = webdriver.Chrome(options=options, service=service) return driver driver = web_driver() driver.get('https://www.google.com') # 保持浏览器打开10秒 time.sleep(10) # 关闭驱动 driver.quit()
内容的提问来源于stack exchange,提问作者confusedcoder
相关产品推荐
相关产品推荐

