【问题标题】:How to fix web3 module AttributeError?如何修复 web3 模块 AttributeError?
【发布时间】:2018-01-10 06:09:47
【问题描述】:

我正在尝试在 python 中使用 web3。

我正在尝试按照http://web3py.readthedocs.io/en/stable/web3.eth.html#web3.eth.Eth中的步骤进行操作

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

但是得到了AttributeError: module 'web3.eth' has no attribute 'getBlock'

我在 python 3 和 python 2.7 中都试过了,得到了相同的结果。

有什么建议吗?

谢谢

【问题讨论】:

    标签: python ethereum web3


    【解决方案1】:

    在调用web3.eth.getBlock 以设置eth 模块函数之前,请确保您正在实例化quickstart docs 中提到的Web3 对象。

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

    查看code for web3.eth 可以看出class Eth(Module): 包含def getBlock。如果您还查看definition of Module,您会看到attach 函数实际上用于使用您想要的行为重新定义web3.ethattach 函数通常在web3/main.py 中调用:

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

    注意module_class 上方的循环之一是Ethmodule_name"eth"

    您可能缺少此逻辑,因此请确保在调用 web3.eth.getBlock 之前实例化 Web3 对象。

    【讨论】:

      【解决方案2】:

      我正在为以太坊网络工作。给定的代码对我有用。

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

      然后写代码web3.eth.getBlock("1028201")

      【讨论】:

        【解决方案3】:

        可以使用web3.eth.get_block API 通过它们的编号或哈希来查找块。块哈希应该是十六进制表示。块号

        按编号获取块

        web3.eth.get_block(12345)
        

        见文档。 https://web3py.readthedocs.io/en/stable/examples.html#looking-up-blocks

        【讨论】:

          【解决方案4】:

          如果有人像我一样来到这里寻找以下错误的解决方案

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

          错误:from web3 import web3 正确:from web3 import Web3 请注意第二个“Web3”中的大写“W”

          【讨论】:

          • 我已经在其他一些答案中看到了正确的from web3 import Web3
          【解决方案5】:

          您使用的语法错误, 属性 eth 属于 WEB3 对象,而不是类本身 试试这个就行了

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

          【讨论】:

            猜你喜欢
            • 2020-12-27
            • 2023-01-15
            • 2019-05-25
            • 2019-08-25
            • 2020-09-03
            • 2020-03-17
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多