You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Ubuntu上启动Python Selenium脚本?启动报错求助

问题与解决方案

问题

  • 执行xvfb-run firefox后启动Python脚本出现错误
  • 直接用python3启动脚本时,抛出错误:
    NotADirectoryError: [Errno 20] Not a directory: '/home/druid/.wdm/drivers/geckodriver/linux64/v0.31.0/geckodriver'
    

涉及的部分代码:

import time
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.wait import WebDriverWait
from webdriver_manager.firefox import GeckoDriverManager
from selenium.webdriver.support import expected_conditions as EC

def main():
    #options = webdriver.FirefoxOptions()
    #options.add_argument("--start-maximized")
    driver = webdriver.Firefox(executable_path=GeckoDriverManager().install())

解决步骤

1. 修复Geckodriver权限

报错本质是geckodriver文件缺少可执行权限,执行命令赋予权限:

chmod +x /home/druid/.wdm/drivers/geckodriver/linux64/v0.31.0/geckodriver

2. 适配Selenium 4.x驱动初始化写法

旧版本executable_path参数在Selenium 4中已被弃用,改用Service类管理驱动,同时添加适配xvfb的浏览器选项:

import time
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.wait import WebDriverWait
from webdriver_manager.firefox import GeckoDriverManager
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.firefox.service import Service

def main():
    # 添加适配无头环境的选项,适配xvfb场景
    options = webdriver.FirefoxOptions()
    options.add_argument('--headless')
    options.add_argument('--no-sandbox')
    options.add_argument('--disable-dev-shm-usage')
    
    # 用Service类指定驱动路径
    service = Service(GeckoDriverManager().install())
    driver = webdriver.Firefox(service=service, options=options)

3. 正确使用xvfb启动脚本

不要单独启动xvfb-run firefox,直接用xvfb包裹Python命令执行脚本,避免环境冲突:

xvfb-run -a python3 your_script.py

内容的提问来源于stack exchange,提问作者aipz

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.17 03:20:43