简体   繁体   中英

How to fix web3 module AttributeError?

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?

Thanks

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 .

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")

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

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'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM