使用Python的Selenium启动Firefox报错,寻求解决方案
Hey there, let's work through why your Selenium script is failing when trying to launch Firefox. First, let's recap your setup to make sure we're aligned:
- You’ve installed Selenium via
pip install selenium - You placed
geckodriver.exein the same directory asFirefox.exe(C:\Program Files\Mozilla Firefox) - Your test code is:
from selenium import webdriver browser = webdriver.Firefox()
And you’re seeing a traceback error starting with:
C:\Users\asd\PycharmProjects\tomato\venv\Scripts\python.exe C:/Users/asd/Downloads/pycharmprojects/tomato/test.py
Traceback (most recent call last):
File "C:/Users/asd/Downloads/pycharmprojects/tomato/test.py", line 2, in
b...
Here are the most common fixes for this issue:
1. Ensure GeckoDriver is in your System PATH
Even though you put geckodriver.exe in Firefox’s directory, that folder might not be added to your Windows System PATH. Windows needs to know where to locate the driver executable when Selenium calls it.
Fix steps:
- Open System Properties (right-click This PC > Properties > Advanced system settings)
- Go to the Advanced tab > click Environment Variables
- Under System Variables, find the
Pathvariable and click Edit - Click New and add
C:\Program Files\Mozilla Firefoxto the list - Click OK to save all changes, then restart your IDE/Python terminal to apply the PATH update
2. Specify GeckoDriver's path directly in your code
If updating the PATH feels tedious, you can point Selenium straight to the driver’s location using the service argument (for Selenium 4+):
from selenium import webdriver from selenium.webdriver.firefox.service import Service service = Service(r'C:\Program Files\Mozilla Firefox\geckodriver.exe') browser = webdriver.Firefox(service=service)
For older Selenium versions, use executable_path:
from selenium import webdriver browser = webdriver.Firefox(executable_path=r'C:\Program Files\Mozilla Firefox\geckodriver.exe')
3. Check for version compatibility between Firefox and GeckoDriver
Mismatched versions are a super common culprit. Make sure your geckodriver.exe version works with your installed Firefox version:
- If you’re running the latest Firefox, grab the newest GeckoDriver release
- For older Firefox builds, look up the GeckoDriver version that supports it (you can find this info in Selenium’s official docs)
4. Fix permission issues
Since C:\Program Files is a protected system directory, your Python script might not have access to geckodriver.exe there. Try moving the driver to a non-system folder (like your project directory C:\Users\asd\PycharmProjects\tomato) and update the path in your code or PATH variable accordingly.
Start with specifying the driver path directly—it’s often the quickest fix. Let me know if you still hit snags!
内容的提问来源于stack exchange,提问作者user159234

