'Web3.py - Unable to import 'web3' even though web3 is installed

I've installed web3 today via pip install web3 and since then I've been trying to import web3 into the current working file without any success.

No matter what I do, I get "Unable to import 'web3'.

Pip list finds web3 (web3 5.19.0).

Code in the file:

import web3

from web3 import Web3, HTTPProvider, TestRPCProvider

infura_url = 'URL'
web3 = Web3(Web3.HTTPProvider(infura_url))

isConnected = web3.isConnected()
blocknumber = web3.eth.blockNumber

Update

I know what's wrong, pip installs packages in C:\Users\USER\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages meanwhile python is looking for the packages in C:\Users\USER\AppData\Roaming\Python\Python39



Solution 1:[1]

You Don't need the first import and it is effecting you'r code cause you'r variable called web3, just delete

import web3

and it should work

Solution 2:[2]

pip list is showing web3 library, after figuring out I found that it is a problem of vs code python editor. Run the following code irrespective of editor error message if run successfully

from web3 import Web3
print(Web3)

It will give output

<class 'web3.main.Web3'>

Then it mean it has some vs code python editor problem but you can ignore warning and use web3 for coding purpose

Solution 3:[3]

You Don't need the first import and it is effecting you're code cause you're variable called web3, just delete

import web3

and for webSocket use it:

Web3(Web3.WebsocketProvider(infura_url))

and for http use it:

Web3(Web3.HTTPProvider(infura_url))

Solution 4:[4]

This is a problem with Visual Studio Code. I tried to open the code with PyCharm and it is working properly.

Solution 5:[5]

you must install visual c ++ build tools // desktop development with c ++ // then you install web3 in the console and it will not give you an error

https://visualstudio.microsoft.com/visual-cpp-build-tools/

Solution 6:[6]

This sounds like an issue with your local version. I would try quitting the app and try again.

Solution 7:[7]

Some suggested that it works despite of the error. But in my case it wasn't. So, the solution for me was installing web3 globally on my local system, outside of the virtual env using pip3 install web3 command. I'm using python3 on Ubuntu 20.04 LTS.

Solution 8:[8]

delete first line of code. also delete import HTTPProvider or use code below

web3 = Web3(HTTPProvider(infura_url))

instead of

web3 = Web3(Web3.HTTPProvider(infura_url))

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Monir Nassan
Solution 2 yash chandel
Solution 3 ali asadi
Solution 4 Andrea Laiena
Solution 5 Nigan
Solution 6 Heather Jane
Solution 7 KhairulBashar
Solution 8 Ashkan