Modulenotfounderror no module named requests как исправить

Requests is not a built in module (does not come with the default python installation), so you will have to install it:

OSX/Linux

Python 2: sudo pip install requests

Python 3: sudo pip3 install requests

if you have pip installed (pip is the package installer for python and should come by default with your python installation).
If pip is installed but not in your path you can use python -m pip install requests (or python3 -m pip install requests for python3)

Alternatively you can also use sudo easy_install -U requests if you have easy_install installed.

Linux

Alternatively you can use your systems package manager:

For centos: sudo yum install python-requests

For Debian/Ubuntu Python2: sudo apt-get install python-requests

For Debian/Ubuntu Python3: sudo apt-get install python3-requests

Windows

Use pip install requests (or pip3 install requests for python3) if you have pip installed and Pip.exe added to the Path Environment Variable. If pip is installed but not in your path you can use python -m pip install requests (or python3 -m pip install requests for python3)

Alternatively from a cmd prompt, use > Patheasy_install.exe requests, where Path is your Python*Scripts folder, if it was installed. (For example: C:Python32Scripts)

If you manually want to add a library to a windows machine, you can download the compressed library, uncompress it, and then place it into the Libsite-packages folder of your python path. (For example: C:Python27Libsite-packages)

From Source (Universal)

For any missing library, the source is usually available at https://pypi.python.org/pypi/. You can download requests here: https://pypi.python.org/pypi/requests

On mac osx and windows, after downloading the source zip, uncompress it and from the termiminal/cmd run python setup.py install from the uncompressed dir.

(source)

Многие новички, при импорте библиотек, сталкиваются с такой ошибкой:

python: no module named requests или как установить библиотеку в python

Очень важное предисловие!

Если вы используете среду разработки PyCharm, то вместо данной статьи смотрите вот эту.

А теперь к теме

Причин может быть несколько:

1. Неправильно указано название

Проверьте, нет ли ошибок в названии библиотеки, которую вы импортируете

python: no module named requests или как установить библиотеку в python

Исправьте ошибки, если они есть, если это не помогло, попробуйте следующий способ

2. Вы не установили библиотеку

Если сообщение об ошибке до сих пор вас беспокоит, то вы просто не установили нужную вам библиотеку.

Сделать это можно так:

1. Нажать комбинацию клавиш Win + R

python: no module named requests или как установить библиотеку в python

2. В открывшемся окне написать cmd и нажать “OK”

python: no module named requests или как установить библиотеку в python

3. В открывшейся командной строке написать pip install [название библиотеки], например pip install requests.

python: no module named requests или как установить библиотеку в python

Готово, библиотека установлена и вы можете пользоваться ей в своей программе.

Если при вводе команды вам выдало ошибку “pip” не является внутренней или внешней командой, исполняемой программой или пакетным файлом, значит при установке python вы не установили pip

Как установить pip

1. Для установки pip нужно переустановить python, для этого скачайте его с официального сайта, или используйте ваш инсталлятор, которым вы устанавливали python ранее.

python: no module named requests или как установить библиотеку в python

2. Запустите инсталлятор, если есть кнопка “Uninstall”, нажмите её, подождите пока python удалится, если такой кнопки нет, перейдите к следующему шагу.

python: no module named requests или как установить библиотеку в python

3. Ещё раз запустите инсталлятор, обязательно выделите галочкой пункт “Add python to PATH” и нажмите “Install Now”.

python: no module named requests или как установить библиотеку в python

4. Подождите пока python установится.

Теперь попробуйте в командной строке написать pip install requests

Если проблема не исчезла, то перейдите но ссылке https://bootstrap.pypa.io/get-pip.py, выделите весь текст, нажав сочетание клавиш Ctrl + A и скопируйте текст нажав сочетание клавиш Ctrl + C.

Создайте на рабочем столе любую папку, откройте её, создайте в ней файл get-pip.py, откройте его и вставьте в него весь скопированный текст, сохраните файл.

python: no module named requests или как установить библиотеку в python

Далее, в верхней части окна, кликните на поле, напишите там cmd и нажмите enter

python: no module named requests или как установить библиотеку в python

Откроется командная строка, в ней напишите python get-pip.py

Начнётся установка pip, после установки вы сможете пользоваться им.

Теперь напишите в командной строке pip install requests, всё заработало!

python: no module named requests или как установить библиотеку в python

Trying to import 'requests'.

Has it installed via pip3 install requests? But still, have this error.

C:UsersVikentiy>pip3 list
Package    Version
---------- ----------
certifi    2018.11.29
chardet    3.0.4
Django     2.1.7
idna       2.8
pip        19.0.2
pytz       2018.9
requests   2.21.0
setuptools 40.6.2
simplejson 3.16.0
urllib3    1.24.1
virtualenv 16.4.0

C:UsersVikentiy>python --version
Python 3.7.2

Error Traceback:

C:UsersVikentiyuntitled2venvScriptspython.exe C:/Users/Vikentiy/untitled2/requeststests.py 
Traceback (most recent call last): 
File "C:/Users/Vikentiy/untitled2/requeststests.py", line 1, in <module> import requests`

Gahan's user avatar

Gahan

4,0554 gold badges24 silver badges44 bronze badges

asked Feb 17, 2019 at 8:37

vikentii's user avatar

8

Another cause of this might be multiple Python versions installations. So if you type in your terminal:

pip3 install requests 

The requests library will be automatically installed to your default python3, for example, Python3.6. However, let’s say you have another Python version, for example, Python3.7, what you should do is:

pip3.7 install requests

This should solve this problem.

If you are running your code in the terminal, you should try:

python3.7 file_to_run.py

answered Nov 8, 2020 at 10:27

Olu Adeyemo's user avatar

Olu AdeyemoOlu Adeyemo

7958 silver badges15 bronze badges

If you’re using PyCharm as IDE, try closing and restarting PyCharm. Move the mouse cursor over the “requests” (with red curly line beneath it), until the red light bulb next to it show up. Select the first option in it, “Install package requests”. PyCharm will take care of the installation from there.

I ran into the same issue and have tried all the solutions here on Stack Overflow.

answered Dec 1, 2019 at 13:11

Egret's user avatar

EgretEgret

4231 gold badge3 silver badges13 bronze badges

If it is installed this will WORK:

c:>python  (or on Mac/Linux "$ python")
>>> import requests
>>> requests.get("http://127.0.0.1")
<Response [200]>

If you see this error when running your script/IDE:

Traceback (most recent call last): File “E:test.py”, line 1, in <module>

import requests
ImportError: No module named requests

Try:

python script.py

Answer is based on https://www.edureka.co/community/84584/python-requests-module-import-error-module-named-requests

Then the trick for me was not to start up a VirtualEnv, I actually found I was running the x64 version of python when I’d installed the requests package into the python 32 bit folder c:program files (x86)python37-32libsite-packages. This is a screenshot from the internet but it shows you how to change the interpreter you’re using – in my case – I need to set it to Python 3.7.4(x86) 32 bit:

enter image description here

answered Oct 13, 2020 at 6:51

Jeremy Thompson's user avatar

Jeremy ThompsonJeremy Thompson

61k33 gold badges184 silver badges313 bronze badges

Run in command prompt
and write command pip install requests in scripts directory

cd Python27scripts
pip install requests

wilkben's user avatar

wilkben

6473 silver badges12 bronze badges

answered May 16, 2020 at 14:28

Sagar Gyanchandani's user avatar

That’s the exact solution which works for me, please follow this:

As like, first try to get the version of the requests module installed previously, this can be find by

pip install requests

Now, you will get the message:

Requirement already satisfied: requests in /opt/anaconda3/lib/python3.8/site-packages (2.24.0)

See, here the version of the requests module i.e., (2.24.0)

Now, the simple basic logic is this like you should install just the previous version of the requests (2.24.0). So, you should now install requests (2.20.0)

For this use command:

pip install requests==2.20.0

Now, I think you can test import requests and this will work fine.

Further, if any error occurs then please let me know in the comments.

Thanks,
HaPpY Coding 🤗

answered Jul 18, 2021 at 17:27

Mayur Gupta's user avatar

Mayur GuptaMayur Gupta

3052 silver badges14 bronze badges

1

If you are using venv (virtual environment), you may need to consider where it’s path. for my case it was outside my project folder. So I had to first install request inside the main python’s path then I recreate venv inside my project.

inside_your_project#python -m venv ./venv

answered Mar 30, 2022 at 19:18

Essiw Sined's user avatar

This issue is due to missing request module in python package .So you can use below command to install and recheck by restarting your IDE

pip install requests

If already installed better to upgrade

pip install --upgrade pip

answered Jan 18, 2022 at 11:36

Vinayak's user avatar

VinayakVinayak

6,0061 gold badge32 silver badges30 bronze badges

requests could be many different sub-modules so like if you are using urllib request it would be

import urllib.request

I would recommend urllib.request because it has worked well in the past.
I’m pretty sure “requests” is pretty old and very finicky and difficult to use. i was trying to access data from a server a few days ago so users wouldn’t have to redownload in order to get updates and instead run code grabbed from my webserver. I tried getting requests to work but to no avail. after some digging around I found urllib which worked like a charm.

for example, this code grabs code from a webpage and executes it:

import urllib.request
page = urllib.request.urlopen('https://pastebin.com/raw/j5LSmvP4')
r = page.read()
exec(r.decode())

also when creating a StackOverflow question, I would recommend showing a code snippet or example as a visual representation to know what the answer-er is dealing with in terms of context.

answered Mar 2 at 17:34

DuckyPolice's user avatar

A common error you may encounter when using Python is modulenotfounderror: no module named ‘requests’. This error occurs when Python cannot detect the Requests library in your current environment. Requests does not come with the default Python installation. This tutorial goes through the exact steps to troubleshoot this error for the Windows, Mac and Linux operating systems.

ModuleNotFoundError: no module named ‘requests’

What is ModuleNotFoundError?

The ModuleNotFoundError occurs when the module you want to use is not present in your Python environment. There are several causes of the modulenotfounderror:

The module’s name is incorrect, in which case you have to check the name of the module you tried to import. Let’s try to import the re module with a double e to see what happens:

import ree
---------------------------------------------------------------------------
ModuleNotFoundError                       Traceback (most recent call last)
1 import ree

ModuleNotFoundError: No module named 'ree'

To solve this error, ensure the module name is correct. Let’s look at the revised code:

import re

print(re.__version__)
2.2.1

You may want to import a local module file, but the module is not in the same directory. Let’s look at an example package with a script and a local module to import. Let’s look at the following steps to perform from your terminal:

mkdir example_package

cd example_package

mkdir folder_1

cd folder_1

vi module.py

Note that we use Vim to create the module.py file in this example. You can use your preferred file editor, such as Emacs or Atom. In module.py, we will import the re module and define a simple function that prints the re version:

import re

def print_re_version():

    print(re.__version__)

Close the module.py, then complete the following commands from your terminal:

cd ../

vi script.py

Inside script.py, we will try to import the module we created.

import module

if __name__ == '__main__':

    mod.print_re_version()

Let’s run python script.py from the terminal to see what happens:

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

To solve this error, we need to point to the correct path to module.py, which is inside folder_1. Let’s look at the revised code:

import folder_1.module as mod

if __name__ == '__main__':

    mod.print_re_version()

When we run python script.py, we will get the following result:

2.2.1

Lastly, you can encounter the modulenotfounderror when you import a module that is not installed in your Python environment. The simplest way to install requests is to use the package manager for Python called pip. The following instructions are for the major Python version 3.

What is requests?

Requests is an HTTP library for Python. Requests allows you to send HTTP/1.1 requests. Requests does not automatically come installed with Python.

How to install requests on Windows Operating System

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

To install requests with pip, run the following command from the command prompt.

pip3 install requests

How to install requests on Mac Operating System

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 requests:

pip3 install requests

How to install requests on Linux Operating System

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

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

pip3 install requests

Check requests Version

Once you have successfully installed requests, you can use two methods to check the version of requests. First, you can use pip show from your terminal.

pip show requests
Name: requests
Version: 2.25.1
Summary: Python HTTP for Humans.
Home-page: https://requests.readthedocs.io
Author: Kenneth Reitz
Author-email: [email protected]
License: Apache 2.0
Location: /Users/Yusufu.Shehu/opt/anaconda3/lib/python3.8/site-packages
Requires: urllib3, chardet, idna, certifi
Required-by: tensorboard, Sphinx, requests-oauthlib, jupyterlab-server, conda, conda-repo-cli, conda-build, anaconda-project, anaconda-client

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

import requests

print(requests.__version__)
2.25.1

Installing requests Using Anaconda

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, you can install requests using the following command:

conda install -c anaconda requests

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 the requests library.

For further reading on ModuleNotFoundErrors, go to the article: How to Solve Python ModuleNotFoundError: No module named ‘ConfigParser’.

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

Have fun and happy researching!

когда я запускаю программу, то выдает ошибку:
ModuleNotFoundError: No module named ‘requests’

он уже установлен через pip install requests, но когда запускаю программу, то все плохо


  • Вопрос задан

    более года назад

  • 662 просмотра

1.Возможно, другой интерпретатор (например requests установлен для 3.x, а по умолчанию запускается 2.х)
2.Возможно, requests установлен в виртуальном окружении, а вы пытаетесь запустить без него (ну или наоборот).

Пригласить эксперта

Вообще,если у тебя стоит линукс, то нужно ввести команду pip3 install requests, что-бы библиотека установилась именно на 3-ю версию питона


  • Показать ещё
    Загружается…

17 мая 2023, в 12:29

20000 руб./за проект

17 мая 2023, в 12:11

1000 руб./за проект

17 мая 2023, в 12:07

15000 руб./за проект

Минуточку внимания

Добавить комментарий