3

I am trying to using web3 in python.

I am trying to follow the steps in http://web3py.readthedocs.io/en/stable/web3.eth.html#web3.eth.Eth

import web3
web3.eth.getBlock("1028201")

But got

AttributeError: module 'web3.eth' has no attribute 'getBlock'

I tried in both python 3 and python 2.7, got the same result.

Any suggestion?

TylerH
  • 20,799
  • 66
  • 75
  • 101
BlueDolphin
  • 9,765
  • 20
  • 59
  • 74

5 Answers5

2

The syntax you're using is wrong, the attribute eth belongs to a WEB3 object, not the class itself try this it shall work


from web3 import Web3
# Create an object from the WEB3 lib
w3 = Web3(Web3.IPCProvider())

#then use the eth attribute on it
w3.eth.getBlock("1028201")
Dharman
  • 30,962
  • 25
  • 85
  • 135
A.MARSHALL
  • 21
  • 3
1

Ensure you are instantiating a Web3 object as mentioned in the quickstart docs before calling into web3.eth.getBlock to setup the eth module functions.

from web3 import Web3, TestRPCProvider
w3 = Web3(TestRPCProvider())

A look at the code for web3.eth shows us that class Eth(Module): contains def getBlock. If you also look at the definition of Module, you see see that the attach function is used to actually redefine web3.eth with the behavior you want. The attach function is normally called in the web3/main.py:

for module_name, module_class in modules.items():
        module_class.attach(self, module_name)

Note in one of the loops above the module_class is Eth and module_name is "eth".

You are likely missing this logic, so ensure you are instantiating a Web3 object before calling into web3.eth.getBlock.

TheoretiCAL
  • 19,461
  • 8
  • 43
  • 65
1

I am working for Ethereum network. Given code works for me.

from web3 import Web3                               
w3 = Web3(Web3.HTTPProvider("https://ropsten.infura.io/"))

And then write code web3.eth.getBlock("1028201")

Varsh
  • 413
  • 9
  • 26
0

Blocks can be looked up by either their number or hash using the web3.eth.get_block API. Block hashes should be in their hexadecimal representation. Block numbers

get a block by number

web3.eth.get_block(12345)

See doc. https://web3py.readthedocs.io/en/stable/examples.html#looking-up-blocks

Toni
  • 670
  • 11
  • 29
0

If anyone landed here in search of solution of below error like me

ImportError: cannot import name 'web3' from 'web3'

wrong: from web3 import web3 correct: from web3 import Web3 Please note capital 'W' in second 'Web3'

Dharman
  • 30,962
  • 25
  • 85
  • 135
CoreCoder
  • 389
  • 1
  • 4
  • 14