在Apache部署的Flask WSGI环境中运行Selenium失败的问题排查
Apache/WSGI部署的Flask项目运行Selenium失败排查与解决
我在虚拟环境(venv)中开发的Flask项目,部署到Apache服务器的WSGI环境后,运行Selenium时出现错误,怀疑是权限问题但迟迟找不到解决办法。
Flask核心代码
from selenium import webdriver from selenium.webdriver import FirefoxOptions from selenium.webdriver.common.by import By from selenium.webdriver.support.wait import WebDriverWait from selenium.webdriver.support import expected_conditions as EC from selenium.webdriver.chrome.service import Service from selenium.webdriver.chrome.options import Options def create_session(): chrome_options = Options() chrome_options.add_argument('--no-sandbox') chrome_options.add_argument('--headless') chrome_options.add_argument('--disable-dev-shm-usage') chrome_options.binary_location="/snap/bin/chromium" chrome_options.add_argument("--log-path='/path/to/app/geckodriver.log'") service = Service('/usr/bin/chromedriver') browser=webdriver.Chrome(service=service, options=chrome_options) browser.get('https://someaddress.com/login')
测试路由
@app.route('/test') def test(): r = create_session()
Apache错误日志(apache2/error.log)
[...] [wsgi:error] [...] [client ...] File "/path/to/app/selenium-stuff.py", line 34, in create_session [...] [wsgi:error] [...] [client ...] browser = webdriver.Firefox(service=service, options=opts) [...] [wsgi:error] [...] [client ...] File "/path/to/app/venv/lib/python3.10/site-packages/selenium/webdriver/firefox/webdriver.py", line 61, in __init__ [...] [wsgi:error] [...] [client ...] self.service.start() [...] [wsgi:error] [...] [client ...] File "/path/to/app/venv/lib/python3.10/site-packages/selenium/webdriver/common/service.py", line 97, in start [...] [wsgi:error] [...] [client ...] self.assert_process_still_running() [...] [wsgi:error] [...] [client ...] File "/path/to/app/venv/lib/python3.10/site-packages/selenium/webdriver/common/service.py", line 110, in assert_process_still_running [...] [wsgi:error] [...] [client ...] raise WebDriverException(f"Service {self._path} unexpectedly exited. Status code was: {return_code}") [...] [wsgi:error] [...] [client ...] selenium.common.exceptions.WebDriverException: Message: Service /snap/bin/geckodriver unexpectedly exited. Status code was: 1
已尝试的解决步骤
- 启用无头模式(headless)
- 切换至Chromium及chrome-driver
geckodriver.log已创建并设置chmod +w权限,但日志内容极少;/snap/bin/geckodriver存在且为全局可执行权限。该函数在两种场景下可正常运行:(a) 直接通过python3命令行调用;(b) 通过Flask开发服务器调用,但在Apache/WSGI环境下无法运行,因此锁定为权限相关问题。
补充测试结果
以普通非特权用户运行/usr/bin/chromedriver可正常工作,但执行sudo -u www-data /usr/bin/chromedriver时出现以下错误:
/user.slice/user-1000.slice/session-2.scope is not a snap cgroup
这表明chromedriver无法以www-data用户运行。曾临时禁用apparmor.service,但无任何改善。
最终解决方案
放弃使用Chromium/chrome-driver,转回Firefox。通过启用开发者模式重装Firefox,规避了部分沙箱权限限制,问题得以解决。
内容的提问来源于stack exchange,提问作者jrs44
相关产品推荐
相关产品推荐

