学习Selenium时遭遇ImportError: cannot import name webdriver问题求助
Hey there, sorry to hear you're hitting this frustrating import error in your virtual environment! Let's go through some practical troubleshooting steps to get this sorted out:
Double-check your Selenium version and import syntax
Selenium's import structure has stayed fairly consistent, but mismatched versions can still cause issues. First, check which version you have installed in your active virtualenv with:pip show selenium
For Selenium 3.x and 4.x, the correct base import should be:from selenium import webdriver
If you're using an extremely old version (pre-3.x), the path might differ—but odds are you just need to ensure your import line matches the version you have.Verify your virtualenv is actually active
It's easy to think you're in the virtualenv when you're still using your global Python. Confirm with:- On Linux/macOS:
which python(the path should point inside your virtualenv folder) - On Windows:
where python
Then runpip listto make sure Selenium is listed in the active environment's installed packages. If it's not, you probably installed it globally by mistake—reinstall it while the virtualenv is active.
- On Linux/macOS:
Reinstall Selenium to fix corrupted files
Sometimes the installation gets borked mid-process. Uninstall and reinstall a stable version to rule this out:pip uninstall selenium -y pip install selenium==4.15.0 # A reliable recent version; adjust if you need a specific oneCheck for filename conflicts
If you have any files in your project namedselenium.pyorwebdriver.py, Python will try to import from those instead of the actual library. Rename any such files immediately—this is a super common gotcha!Rebuild your virtualenv from scratch
If none of the above works, your virtualenv might have been corrupted during creation. Delete it and start fresh:# Linux/macOS rm -rf your_virtualenv_name virtualenv your_virtualenv_name source your_virtualenv_name/bin/activate pip install selenium [other required packages] # Windows (Command Prompt) rmdir /s your_virtualenv_name virtualenv your_virtualenv_name your_virtualenv_name\Scripts\activate.bat pip install selenium [other required packages]
If you're still stuck after trying these steps, sharing a snippet of your import code and the exact Selenium version you're using would help narrow things down further.
内容的提问来源于stack exchange,提问作者Josh Frazier

