Меню

From selenium import webdriver выдает ошибку

I just installed Selenium 2 by doing pip install selenium and just copied some example tests to make sure that it’s working:

from selenium import webdriver
from selenium.webdriver.common.keys import Keys

driver = webdriver.Firefox()
driver.get("http://www.python.org")
assert "Python" in driver.title
elem = driver.find_element_by_name("q")
elem.send_keys("selenium")
elem.send_keys(Keys.RETURN)
assert "Google" in driver.title
driver.close()

I saved that as test.py in a sub-folder in my Home folder on my Mac, but when ever I run python test.py, I get the following output:

Traceback (most recent call last):
  File "demo.py", line 1, in <module>
    from selenium import webdriver
ImportError: cannot import name webdriver

If I move that file into my Home directory, it works. If you couldn’t tell, I’m just getting started with Selenium and programming. Any help with this would be much appreciated.

asked Sep 15, 2011 at 6:43

Cass's user avatar

It sounds like you have some other module in your path named «selenium», and python is trying to import that one because it comes earlier in your python path. Did you name your file «selenium.py», for example?

To debug, import selenium with a simple import selenium then print the name of the file that was imported with print selenium.__file__

If you have a file named «selenium.py» which is not the proper selenium library, in addition to renaming or removing it, make sure you also delete «selenium.pyc», or python will continue to try to import from the .pyc file.

answered Sep 15, 2011 at 12:43

Bryan Oakley's user avatar

Bryan OakleyBryan Oakley

359k50 gold badges529 silver badges669 bronze badges

4

Old question, but I did the same thing too. Named my file ‘selenium.py’ and it gave this very error message. Renamed the file to something else, but still got the same error. The problem was, that the selenium.pyc file had been created, since I ran the script from the terminal. Removed the .pyc file and it ran like a charm!

answered Sep 27, 2012 at 8:09

Kanuj Bhatnagar's user avatar

Kanuj BhatnagarKanuj Bhatnagar

1,3101 gold badge14 silver badges24 bronze badges

3

Though the question seems to be inactive quite a long time, I had the same message/similar problem, and none of the answers above fit.

The site http://kevingann.blogspot.de/2012/11/troubleshooting-pydev-and-selenium.html gave the crucial hint.

Selenium occured twice, once in the system libs as egg, and the «installed» version in the external libs. Smashing the egg did the trick.

Hope this will help someone too

answered Jun 6, 2014 at 13:10

Lord_Gestalter's user avatar

Lord_GestalterLord_Gestalter

5001 gold badge5 silver badges14 bronze badges

1

the error ImportError: cannot import name webdriver or no module selenium2library was resolved by placing selenium folder directly under Lib instead of site_packages

Robert's user avatar

Robert

5,26743 gold badges65 silver badges115 bronze badges

answered Aug 27, 2015 at 9:42

Selenium2_user's user avatar

Error in Pycharm «Cannot find reference ‘Chrome’ in ‘imported module selenium.webdriver'» got resolved after copying selenium dir from site-packages to lib.
Can be verified as stated above

import selenium
print (selenium.__file__)

answered May 28, 2016 at 22:47

Karan Thakur's user avatar

Sethe project interpreter as actual python.exe

I am able to run successfully the code below:

from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.chrome.options import Options
import time

opts = Options()
prefs = {"profile.managed_default_content_settings.images": 2}  
opts.add_experimental_option("prefs", prefs)


# enter complete path of chrome driver as argument to below line of code 
browser = webdriver.Chrome('C:\Users\BLR153\AppData\Local\Programs\Python\Python36-32\selenium\chromedriver.exe')
# browser = webdriver.Firefox()

browser.get('http://www.google.com')

time.sleep(10)

browser.quit()

answered Jul 15, 2018 at 6:28

Suresh Parimi's user avatar

Just name your pytnon file NOT selenium.py !!!
It is not looking for webdriver in selenium, but in your file, where you are trying to connect it

answered Jun 23, 2021 at 8:33

Kirill Levunin's user avatar

1

  1. Make sure that you have only one python version installed
  2. Install pip
  3. Install selenium using pip
    pip install selenium
  4. Run the script

Hope that helps.

answered Dec 7, 2016 at 20:54

Suresh Ganta's user avatar

I just installed Selenium 2 by doing pip install selenium and just copied some example tests to make sure that it’s working:

from selenium import webdriver
from selenium.webdriver.common.keys import Keys

driver = webdriver.Firefox()
driver.get("http://www.python.org")
assert "Python" in driver.title
elem = driver.find_element_by_name("q")
elem.send_keys("selenium")
elem.send_keys(Keys.RETURN)
assert "Google" in driver.title
driver.close()

I saved that as test.py in a sub-folder in my Home folder on my Mac, but when ever I run python test.py, I get the following output:

Traceback (most recent call last):
  File "demo.py", line 1, in <module>
    from selenium import webdriver
ImportError: cannot import name webdriver

If I move that file into my Home directory, it works. If you couldn’t tell, I’m just getting started with Selenium and programming. Any help with this would be much appreciated.

asked Sep 15, 2011 at 6:43

Cass's user avatar

It sounds like you have some other module in your path named «selenium», and python is trying to import that one because it comes earlier in your python path. Did you name your file «selenium.py», for example?

To debug, import selenium with a simple import selenium then print the name of the file that was imported with print selenium.__file__

If you have a file named «selenium.py» which is not the proper selenium library, in addition to renaming or removing it, make sure you also delete «selenium.pyc», or python will continue to try to import from the .pyc file.

answered Sep 15, 2011 at 12:43

Bryan Oakley's user avatar

Bryan OakleyBryan Oakley

359k50 gold badges529 silver badges669 bronze badges

4

Old question, but I did the same thing too. Named my file ‘selenium.py’ and it gave this very error message. Renamed the file to something else, but still got the same error. The problem was, that the selenium.pyc file had been created, since I ran the script from the terminal. Removed the .pyc file and it ran like a charm!

answered Sep 27, 2012 at 8:09

Kanuj Bhatnagar's user avatar

Kanuj BhatnagarKanuj Bhatnagar

1,3101 gold badge14 silver badges24 bronze badges

3

Though the question seems to be inactive quite a long time, I had the same message/similar problem, and none of the answers above fit.

The site http://kevingann.blogspot.de/2012/11/troubleshooting-pydev-and-selenium.html gave the crucial hint.

Selenium occured twice, once in the system libs as egg, and the «installed» version in the external libs. Smashing the egg did the trick.

Hope this will help someone too

answered Jun 6, 2014 at 13:10

Lord_Gestalter's user avatar

Lord_GestalterLord_Gestalter

5001 gold badge5 silver badges14 bronze badges

1

the error ImportError: cannot import name webdriver or no module selenium2library was resolved by placing selenium folder directly under Lib instead of site_packages

Robert's user avatar

Robert

5,26743 gold badges65 silver badges115 bronze badges

answered Aug 27, 2015 at 9:42

Selenium2_user's user avatar

Error in Pycharm «Cannot find reference ‘Chrome’ in ‘imported module selenium.webdriver'» got resolved after copying selenium dir from site-packages to lib.
Can be verified as stated above

import selenium
print (selenium.__file__)

answered May 28, 2016 at 22:47

Karan Thakur's user avatar

Sethe project interpreter as actual python.exe

I am able to run successfully the code below:

from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.chrome.options import Options
import time

opts = Options()
prefs = {"profile.managed_default_content_settings.images": 2}  
opts.add_experimental_option("prefs", prefs)


# enter complete path of chrome driver as argument to below line of code 
browser = webdriver.Chrome('C:\Users\BLR153\AppData\Local\Programs\Python\Python36-32\selenium\chromedriver.exe')
# browser = webdriver.Firefox()

browser.get('http://www.google.com')

time.sleep(10)

browser.quit()

answered Jul 15, 2018 at 6:28

Suresh Parimi's user avatar

Just name your pytnon file NOT selenium.py !!!
It is not looking for webdriver in selenium, but in your file, where you are trying to connect it

answered Jun 23, 2021 at 8:33

Kirill Levunin's user avatar

1

  1. Make sure that you have only one python version installed
  2. Install pip
  3. Install selenium using pip
    pip install selenium
  4. Run the script

Hope that helps.

answered Dec 7, 2016 at 20:54

Suresh Ganta's user avatar

I’m trying to write a script to check a website. It’s the first time I’m using selenium. I’m trying to run the script on a OSX system. Although I checked in /Library/Python/2.7/site-packages and selenium-2.46.0-py2.7.egg is present, when I run the script it keeps telling me that there is no selenium module to import.

This is the log that I get when I run my code:

Traceback (most recent call last):
  File "/Users/GiulioColleluori/Desktop/Class_Checker.py", line 10, in <module>
    from selenium import webdriver
ImportError: No module named 'selenium'

Dharman's user avatar

Dharman

29.2k21 gold badges79 silver badges131 bronze badges

asked Jun 30, 2015 at 20:13

Giulio Colleluori's user avatar

0

If you have pip installed you can install selenium like so.

pip install selenium

or depending on your permissions:

sudo pip install selenium

For python3:

sudo pip3 install selenium

As you can see from this question pip vs easy_install pip is a more reliable package installer as it was built to improve easy_install.

I would also suggest that when creating new projects you do so in virtual environments, even a simple selenium project. You can read more about virtual environments here. In fact pip is included out of the box with virtualenv!

answered Jun 30, 2015 at 21:46

gffbss's user avatar

2

I had the exact same problem and it was driving me crazy (Windows 10 and VS Code 1.49.1)

Other answers talk about installing Selenium, but it’s clear to me that you’ve already did that, but you still get the ImportError: No module named 'selenium'.

So, what’s going on?

Two things:

  1. You installed Selenium in this folder /Library/Python/2.7/site-packages and selenium-2.46.0-py2.7.egg
  2. But you’re probably running a version of Python, in which you didn’t install Selenium. For instance: /Library/Python/3.8/site-packages… you won’t find Selenium installed here and that’s why the module isn’t found.

The solution?
You have to install selenium in the same directory to the Python version you’re using or change the interpreter to match the directory where Selenium is installed.

In VS Code you change the interpreter here (at the bottom left corner of the screen)
enter image description here

Ready! Now your Python interpreter should find the module.

answered Oct 3, 2020 at 15:08

Guzman Ojero's user avatar

Guzman OjeroGuzman Ojero

2,38219 silver badges20 bronze badges

1

For python3, on a Mac you must use pip3 to install selenium.

sudo pip3 install selenium

answered May 18, 2018 at 0:01

Brian's user avatar

BrianBrian

4906 silver badges11 bronze badges

It’s 2020 now, use python3 consistently

  • pip3 install selenium
  • python3 xxx.py

I meet the same problem when I install selenium using pip3, but run scripts using python.

Samsul Islam's user avatar

Samsul Islam

2,5282 gold badges16 silver badges23 bronze badges

answered Mar 19, 2020 at 8:11

Lebecca's user avatar

LebeccaLebecca

2,24612 silver badges31 bronze badges

1

If you are using Anaconda or Spyder in windows, install selenium by this code in cmd:

conda install selenium

If you are using Pycharm IDE in windows, install selenium by this code in cmd:

pip install selenium

answered Jan 10, 2019 at 20:00

Hamed Baziyad's user avatar

Hamed BaziyadHamed Baziyad

1,8445 gold badges27 silver badges38 bronze badges

I had the same problem. Using sudo python3 -m pip install selenium may work.

Samsul Islam's user avatar

Samsul Islam

2,5282 gold badges16 silver badges23 bronze badges

answered Aug 31, 2019 at 16:40

tachish's user avatar

tachishtachish

711 silver badge1 bronze badge

Your IDE might be pointing to a different installation of Python than where Selenium is installed.

I’m using Eclipse and when I ran ‘quick auto-configure’ under:

Preferences > PyDev > Interpreters > Python Interpreter

it pointed to a different version of Python than where pip or easy_install actually installed it.

Selenium worked from the Terminal so I determined which version of python my Terminal was using by running this:

python -c "import sys; print(sys.path)"

then had Eclipse point to that same location, which for me on my 10.11 Mac was here:

/Library/Frameworks/Python.framework/Versions/Current/bin/python2.7/

You can run «Advanced Auto-Config» as well to see all of the installed versions of python and select the one you want to use. When I selected that same location using «Advanced Auto-Config» it finally showed me the Selenium folder as it went through the configuration steps.

answered Jun 16, 2017 at 23:27

mindmischief's user avatar

1

If pip isn’t already installed, then first try to bootstrap it from the standard library:

sudo python -m ensurepip --default-pip

Ensure pip, setuptools, and wheel are up to date

sudo python -m pip install --upgrade pip setuptools wheel

Now Install Selenium

sudo pip install selenium

Now run your runner.

Hope this helps. Happy Coding !!

answered Dec 4, 2019 at 10:32

Saif Siddiqui's user avatar

Saif SiddiquiSaif Siddiqui

7781 gold badge12 silver badges33 bronze badges

I ran into the same problem with pycharm where my modules wouldn’t import after installing them on ubuntu with pip.

If you go File-> Settings -> Project > Python Interpreter

You can click the ‘+’ on the right hand side and import modules into the interpreter.

Not sure if that’s your issue but hope this helps.

answered Aug 10, 2020 at 10:06

Ehgriez's user avatar

2

Even though the egg file may be present, that does not necessarily mean that it is installed. Check out this previous answer for some hint:

How to install Selenium WebDriver on Mac OS

Community's user avatar

answered Jun 30, 2015 at 20:35

Steven Correia's user avatar

2

I had a similar problem.
It turned out that I had an alias defined for python like so:

alias python=/usr/bin/python3

Apparently virtualenv does not check or update your aliases.

So the solution for me was to remove the alias:

unalias python

Now when I run python, I get the one from the virtual environment.
Problem solved.

Samsul Islam's user avatar

Samsul Islam

2,5282 gold badges16 silver badges23 bronze badges

answered Aug 18, 2019 at 15:27

nahurmf's user avatar

make easy install again by downloading selenium webdriver from its website it is not installed properly.

Edit 1:
extract the .tar.gz folder go inside the directory and run python setup.py install from terminal.make sure you have installed setuptools.

answered Jun 30, 2015 at 20:47

as1992's user avatar

as1992as1992

531 silver badge8 bronze badges

2

Navigate to your scripts folder in Python directory (C:Python27Scripts) and open command line there (Hold shift and right click then select open command window here). Run pip install -U selenium

If you don’t have pip installed, go ahead and install pip first

answered Aug 1, 2017 at 6:32

Rashid's user avatar

0

pip3 install selenium

Try this if you have python3.

answered Dec 29, 2018 at 21:42

Wimukthi Rajapaksha's user avatar

install urllib3

!pip3 install urllib3

import urllib3

than install it

!pip3 install selenium

import selenium

answered Apr 26, 2020 at 18:24

Sara Bouraya's user avatar

1

first you should be sure that selenium is installed in your system.

then install pycharm https://itsfoss.com/install-pycharm-ubuntu/

now if an of packages are not installed it will show red underlines. click on it and install from pycharm.

like for this case click on selenium option in import statement, there you would getting some options. click on install selenium. it will install and automatically run the code successfully if all your drivers are placed in proper directories.

answered May 15, 2017 at 6:51

Rohit sai's user avatar

Rohit saiRohit sai

1191 silver badge10 bronze badges

Windows:

pip install selenium

Unix:

sudo pip install selenium

Paul Roub's user avatar

Paul Roub

36.2k27 gold badges82 silver badges89 bronze badges

answered Aug 17, 2019 at 19:48

Gunjan Paul's user avatar

Gunjan PaulGunjan Paul

4935 silver badges11 bronze badges

While pip install might work. Please check the project structure and see if there is no virtual environment already (It is a good practice to have one) created in the project. If there is, activate it with source <name_of_virtual_env>/bin/activate (for MacOS) and venvScriptsActivate.ps1 (for Windows powershell) or venvScriptsactivate.bat (for Windows cmd). then pip install selenium into the environment.

If it isn’t,
check if you have a virtual environment with virtualenv --version
If it displays an error, install it with pip install virtualenv
then create a virtual environment with
virtualenv <name_of_virtual_env> (Both Windows and MacOS)or

python -m venv <name_of_virtual_env> (Windows Only)

then activate the virtual environment
with
source <name_of_virtual_env>/bin/activate (for MacOS) and
venvScriptsActivate.ps1 (for Windows powershell) or
venvScriptsactivate.bat (for Windows cmd).
then install selenium with pip install -U selenium (it will install the latest version).
If it doesn’t display an error, just create a virtual environment in the project, activate it and install selenium inside of it.

answered Oct 2, 2020 at 11:49

i_m_sanguine's user avatar

I was having the same issue when using python 3 with conda distribution, trying to run code on Jupyter in a custom virtualenv.
I tried manually installing, installing with pip3, conda etc in anaconda prompt repeatedly but continued to get the import error.
Finally solved it by installing it in the Jupyter Tab itself.
in Jupyter, in a line, run conda install selenium
That’s it
(If you’re facing a similar env that is)

answered Jun 23, 2021 at 2:27

Kriticoder's user avatar

KriticoderKriticoder

931 silver badge6 bronze badges

I had same issue and tried all that are mentioned above but none work for me until I saw py -m pip install -U selenium

answered Jun 19, 2022 at 14:04

MacDonald Ejime  Oghenefejiro's user avatar

Error:

ModuleNotFoundError: No module named ‘selenium’

Solutions:

pip

pip install selenium

pip3

pip3 install selenium

answered Aug 31, 2022 at 7:26

Shehan Jayalath's user avatar

If I use Start Debugging or Run Without Debugging it should run or debug the following script.

from selenium import webdriver

browser = webdriver.Chrome()
browser.get('https://google.com')

In vscode if I use Start Debugging or Run Without Debugging it throws error ModuleNotFoundError: No module named 'selenium'.

vscode Peek Problem shows Import "selenium" could not be resolved Pylance (reportMissingImports).

Just to be clear, if I use python3 google-search.py in terminal, it works.

from selenium import webdriver
    
browser = webdriver.Chrome()
browser.get('https://google.com')
(.venv) ...DataBackup/_Work/_EverythingBooks/_PythonScript:master*...✕1%  cd /media/ismail/WDPurple/_DataBackup/_Work/_EverythingBooks/_PythonScript ; /usr/bin/env /media/ismail/WDPurple/_DataBackup/_Work/_EverythingBooks/_PythonScript/.venv/bin/python /home/ismail/.vscode/extensions/ms-python.python-2020.9.112786/pythonFiles/lib/python/debugpy/launcher 35597 -- /media/ismail/WDPurple/_DataBackup/_Work/_EverythingBooks/_PythonScript/google-search.py 
Traceback (most recent call last):
  File "/media/ismail/WDPurple/_DataBackup/_Work/_EverythingBooks/_PythonScript/google-search.py", line 1, in <module>
    from selenium import webdriver
ModuleNotFoundError: No module named 'selenium'

Quick Fix: Python raises the ImportError: No module named 'selenium' when it cannot find the library selenium. The most frequent source of this error is that you haven’t installed selenium explicitly with pip install selenium. Alternatively, you may have different Python versions on your computer, and selenium is not installed for the particular version you’re using.

Problem Formulation

You’ve just learned about the awesome capabilities of the selenium library and you want to try it out, so you start your code with the following statement:

import selenium

This is supposed to import the selenium library into your (virtual) environment. However, it only throws the following ImportError: No module named selenium:

>>> import selenium
Traceback (most recent call last):
  File "<pyshell#6>", line 1, in <module>
    import selenium
ModuleNotFoundError: No module named 'selenium'

Solution Idea 1: Install Library selenium

The most likely reason is that Python doesn’t provide selenium in its standard library. You need to install it first!

Before being able to import the selenium module, you need to install it using Python’s package manager pip. Make sure pip is installed on your machine.

To fix this error, you can run the following command in your Windows shell:

$ pip install selenium

This simple command installs selenium in your virtual environment on Windows, Linux, and MacOS. It assumes that your pip version is updated. If it isn’t, use the following two commands in your terminal, command line, or shell (there’s no harm in doing it anyways):

$ python -m pip install --upgrade pip
$ pip install selenium

💡 Note: Don’t copy and paste the $ symbol. This is just to illustrate that you run it in your shell/terminal/command line.

Solution Idea 2: Fix the Path

The error might persist even after you have installed the selenium library. This likely happens because pip is installed but doesn’t reside in the path you can use. Although pip may be installed on your system the script is unable to locate it. Therefore, it is unable to install the library using pip in the correct path.

To fix the problem with the path in Windows follow the steps given next.

Step 1: Open the folder where you installed Python by opening the command prompt and typing where python

Step 2: Once you have opened the Python folder, browse and open the Scripts folder and copy its location. Also verify that the folder contains the pip file.

Step 3: Now open the Scripts directory in the command prompt using the cd command and the location that you copied previously.

Step 4: Now install the library using pip install selenium command. Here’s an analogous example:

After having followed the above steps, execute our script once again. And you should get the desired output.

🌍 Recommended Tutorial: How to Install Selenium on PyCharm?

Other Solution Ideas

  • The ModuleNotFoundError may appear due to relative imports. You can learn everything about relative imports and how to create your own module in this article.
  • You may have mixed up Python and pip versions on your machine. In this case, to install selenium for Python 3, you may want to try python3 -m pip install selenium or even pip3 install selenium instead of pip install selenium
  • If you face this issue server-side, you may want to try the command pip install --user selenium
  • If you’re using Ubuntu, you may want to try this command: sudo apt install selenium
  • You can check out our in-depth guide on installing selenium here.
  • You can also check out this article to learn more about possible problems that may lead to an error when importing a library.

Understanding the “import” Statement

import selenium

In Python, the import statement serves two main purposes:

  • Search the module by its name, load it, and initialize it.
  • Define a name in the local namespace within the scope of the import statement. This local name is then used to reference the accessed module throughout the code.

What’s the Difference Between ImportError and ModuleNotFoundError?

What’s the difference between ImportError and ModuleNotFoundError?

Python defines an error hierarchy, so some error classes inherit from other error classes. In our case, the ModuleNotFoundError is a subclass of the ImportError class.

You can see this in this screenshot from the docs:

You can also check this relationship using the issubclass() built-in function:

>>> issubclass(ModuleNotFoundError, ImportError)
True

Specifically, Python raises the ModuleNotFoundError if the module (e.g., selenium) cannot be found. If it can be found, there may be a problem loading the module or some specific files within the module. In those cases, Python would raise an ImportError.

If an import statement cannot import a module, it raises an ImportError. This may occur because of a faulty installation or an invalid path. In Python 3.6 or newer, this will usually raise a ModuleNotFoundError.

Related Videos

The following video shows you how to resolve the ImportError:

How to Fix : “ImportError: Cannot import name X” in Python?

The following video shows you how to import a function from another folder—doing it the wrong way often results in the ModuleNotFoundError:

How to Call a Function from Another File in Python?

How to Fix “ModuleNotFoundError: No module named ‘selenium’” in PyCharm

If you create a new Python project in PyCharm and try to import the selenium library, it’ll raise the following error message:

Traceback (most recent call last):
  File "C:/Users/.../main.py", line 1, in <module>
    import selenium
ModuleNotFoundError: No module named 'selenium'

Process finished with exit code 1

The reason is that each PyCharm project, per default, creates a virtual environment in which you can install custom Python modules. But the virtual environment is initially empty—even if you’ve already installed selenium on your computer!

Here’s a screenshot exemplifying this for the pandas library. It’ll look similar for selenium.

The fix is simple: Use the PyCharm installation tooltips to install Pandas in your virtual environment—two clicks and you’re good to go!

First, right-click on the pandas text in your editor:

Second, click “Show Context Actions” in your context menu. In the new menu that arises, click “Install Pandas” and wait for PyCharm to finish the installation.

The code will run after your installation completes successfully.

As an alternative, you can also open the Terminal tool at the bottom and type:

$ pip install selenium

If this doesn’t work, you may want to set the Python interpreter to another version using the following tutorial: https://www.jetbrains.com/help/pycharm/2016.1/configuring-python-interpreter-for-a-project.html

You can also manually install a new library such as selenium in PyCharm using the following procedure:

  • Open File > Settings > Project from the PyCharm menu.
  • Select your current project.
  • Click the Python Interpreter tab within your project tab.
  • Click the small + symbol to add a new library to the project.
  • Now type in the library to be installed, in your example Pandas, and click Install Package.
  • Wait for the installation to terminate and close all popup windows.

Here’s an analogous example:

Here’s a full guide on how to install a library on PyCharm.

  • How to Install a Library on PyCharm

While working as a researcher in distributed systems, Dr. Christian Mayer found his love for teaching computer science students.

To help students reach higher levels of Python success, he founded the programming education website Finxter.com. He’s author of the popular programming book Python One-Liners (NoStarch 2020), coauthor of the Coffee Break Python series of self-published books, computer science enthusiast, freelancer, and owner of one of the top 10 largest Python blogs worldwide.

His passions are writing, reading, and coding. But his greatest passion is to serve aspiring coders through Finxter and help them to boost their skills. You can join his free email academy here.

A common error you may encounter when using Python is modulenotfounderror: no module named ‘selenium’.

This error occurs when the Python interpreter cannot detect the Selenium library in your current environment.

This tutorial goes through the exact steps to troubleshoot this error for the Windows, Mac and Linux operating systems.


Table of contents

  • ModuleNotFoundError: no module named ‘selenium’
    • What is Selenium?
    • How to Install Selenium on Windows Operating System
      • Selenium installation on Windows Using pip
    • How to Install Selenium on Mac Operating System using pip
    • How to Install Selenium on Linux Operating Systems
      • Installing pip for Ubuntu, Debian, and Linux Mint
      • Installing pip for CentOS 8 (and newer), Fedora, and Red Hat
      • Installing pip for CentOS 6 and 7, and older versions of Red Hat
      • Installing pip for Arch Linux and Manjaro
      • Installing pip for OpenSUSE
      • Selenium installation on Linux with Pip
  • Installing Selenium Using Anaconda
    • Check Selenium Version
  • Summary

ModuleNotFoundError: no module named ‘selenium’

What is Selenium?

Selenium is a suite of tools for automating web browsers. You can use Selenium to automate web applications for testing purposes, though it is not only for testing.

The simplest way to install Selenium is to use the package manager for Python called pip. The following installation instructions are for the major Python version 3.

How to Install Selenium on Windows Operating System

First, you need to download and install Python on your PC. Ensure you select the install launcher for all users and Add Python to PATH checkboxes. The latter ensures the interpreter is in the execution path. Pip is automatically on Windows for Python versions 2.7.9+ and 3.4+.

You can check your Python version with the following command:

python3 --version

You can install pip on Windows by downloading the installation package, opening the command line and launching the installer. You can install pip via the CMD prompt by running the following command.

python get-pip.py

You may need to run the command prompt as administrator. Check whether the installation has been successful by typing.

pip --version

Selenium installation on Windows Using pip

To install Selenium, run the following command from the command prompt.

pip3 install selenium

How to Install Selenium on Mac Operating System using pip

Open a terminal by pressing command (⌘) + Space Bar to open the Spotlight search. Type in terminal and press enter. To get pip, first ensure you have installed Python3:

python3 --version
Python 3.8.8

Download pip by running the following curl command:

curl https://bootstrap.pypa.io/get-pip.py -o get-pip.py

The curl command allows you to specify a direct download link. Using the -o option sets the name of the downloaded file.

Install pip by running:

python3 get-pip.py

From the terminal, use pip3 to install Selenium:

pip3 install selenium

How to Install Selenium on Linux Operating Systems

All major Linux distributions have Python installed by default. However, you will need to install pip. You can install pip from the terminal, but the installation instructions depend on the Linux distribution you are using. You will need root privileges to install pip. Open a terminal and use the commands relevant to your Linux distribution to install pip.

Installing pip for Ubuntu, Debian, and Linux Mint

sudo apt install python-pip3

Installing pip for CentOS 8 (and newer), Fedora, and Red Hat

sudo dnf install python-pip3

Installing pip for CentOS 6 and 7, and older versions of Red Hat

sudo yum install epel-release

sudo yum install python-pip3

Installing pip for Arch Linux and Manjaro

sudo pacman -S python-pip

Installing pip for OpenSUSE

sudo zypper python3-pip

Selenium installation on Linux with Pip

Once you have installed pip, you can install Selenium using:

pip3 install selenium

Installing Selenium Using Anaconda

First, to create a conda environment to install PIL.

conda create -n selenium python=3.6 

Then activate the selenium container. You will see “selenium” in parentheses next to the command line prompt.

source activate selenium

Now you’re ready to install Selenium using conda.

Anaconda is a distribution of Python and R for scientific computing and data science. You can install Anaconda by going to the installation instructions. Once you have installed Anaconda and created your conda environment, you can install Selenium using one of the following commands:

conda install -c conda-forge selenium

Check Selenium Version

Once you have successfully installed Selenium, you can check the version of Selenium. If you used pip to install Selenium, you can use pip show from your terminal.

pip show selenium
Name: selenium
Version: 4.1.0

Second, within your python program, you can import selenium and then reference the __version__ attribute:

import selenium

print(selenium.__version__)
4.1.0

If you used conda to install Selenium, you could check the version using the following command:

conda list -f selenium
# Name                    Version                   Build  Channel
selenium                  3.141.0         py36hfa26744_1002    conda-forge

Summary

Congratulations on reading to the end of this tutorial. The modulenotfounderror occurs if you misspell the module name, incorrectly point to the module path or do not have the module installed in your Python environment. If you do not have the module installed in your Python environment, you can use pip to install the package. However, you must ensure you have pip installed on your system. You can also install Anaconda on your system and use the conda install command to install Selenium.

Go to the online courses page on Python to learn more about Python for data science and machine learning.

For further reading on missing modules in Python, go to the article: How to Solve Python ModuleNotFoundError: no module named ‘urllib2’.

Have fun and happy researching!

0 0 голоса
Рейтинг статьи
Подписаться
Уведомить о
guest

0 комментариев
Старые
Новые Популярные
Межтекстовые Отзывы
Посмотреть все комментарии

А вот еще интересные материалы:

  • Яшка сломя голову остановился исправьте ошибки
  • Ясность цели позволяет целеустремленно добиваться намеченного исправьте ошибки
  • Ясность цели позволяет целеустремленно добиваться намеченного где ошибка
  • From keras models import sequential ошибка
  • From imageai detection import objectdetection ошибка