Python3使用Selenium WebDriver遇SessionNotCreatedException问题求助
SessionNotCreatedException with Selenium & Firefox on Ubuntu Hey David, let's work through this frustrating SessionNotCreatedException you're hitting. I've dealt with similar version mismatch and path issues before, so here are actionable steps to get your Selenium script running:
1. Double-Check Version Compatibility
This is the #1 culprit for this error. Selenium, Firefox, and geckodriver have strict version requirements—mixing mismatched versions will break things every time. Here's a quick compatibility cheat sheet:
- Selenium 4.x: Requires Firefox 90+, geckodriver 0.30+
- Selenium 3.x: Works with Firefox 70–89, geckodriver 0.26–0.29
To check your current versions, run these commands in your shell:
- Firefox:
firefox --version - Selenium:
pip show selenium | grep Version - Geckodriver:
geckodriver --version
If they don't align, download matching versions from official releases (just search for the correct geckodriver/Firefox builds for your Selenium version).
2. Manually Specify Geckodriver Path
Sometimes Ubuntu doesn't add geckodriver to your system PATH automatically. Tell Selenium exactly where to find it with this code tweak:
from selenium import webdriver from selenium.webdriver.firefox.service import Service # Replace with your actual geckodriver path (e.g., /usr/local/bin/geckodriver) geckodriver_path = "/path/to/your/geckodriver" service = Service(geckodriver_path) browser = webdriver.Firefox(service=service)
3. Confirm Firefox Binary Location
If Firefox is installed in a non-default spot (like a custom directory), Selenium might fail to locate it. Add the binary path to your options:
from selenium import webdriver from selenium.webdriver.firefox.service import Service from selenium.webdriver.firefox.options import Options options = Options() # Replace with your Firefox path (common path: /usr/bin/firefox) options.binary_location = "/usr/bin/firefox" service = Service("/path/to/your/geckodriver") browser = webdriver.Firefox(service=service, options=options)
4. Install Missing System Dependencies
Ubuntu sometimes lacks libraries needed for Firefox to run interactively or headless. Install these core dependencies:
sudo apt-get update && sudo apt-get install -y libgtk-3-0 libdbus-glib-1-2 libx11-xcb1 libxtst6
5. Test Headless Mode (If Running in a Shell)
If you're using an interactive shell without a GUI (like SSH), Firefox needs to run in headless mode. Modify your code to include this:
from selenium import webdriver from selenium.webdriver.firefox.options import Options options = Options() options.add_argument("--headless=new") # Use "--headless" for older Firefox versions browser = webdriver.Firefox(options=options)
If none of these steps work, share the exact versions of Selenium, Firefox, and geckodriver you're using, and we can dig deeper!
内容的提问来源于stack exchange,提问作者David Wallace

