Web3.py入门笔记
- 互联网
- 2025-08-27 20:15:01

Web3.py 学习笔记 📚 1. Web3.py 简介 🌟
Web3.py 是一个 Python 库,用于与以太坊区块链进行交互。它就像是连接 Python 程序和以太坊网络的桥梁。
官方文档
1.1 主要功能 查询区块链数据(余额、交易等)发送交易与智能合约交互管理以太坊账户 2. 安装和配置 🔧 2.1 安装 # 使用 pip 安装 pip install web3 # 或使用 conda 安装 conda install -c conda-forge web3 2.2 基础配置 from web3 import Web3 # 连接到以太坊网络(这里使用 Infura 提供的节点) w3 = Web3(Web3.HTTPProvider(' mainnet.infura.io/v3/YOUR-PROJECT-ID')) # 检查是否连接成功 print(f"是否连接成功: {w3.is_connected()}") 3. 基础操作示例 💡 3.1 查询账户余额 def check_eth_balance(address): # 确保地址格式正确 if not w3.is_address(address): return "无效的以太坊地址" # 获取余额(单位:Wei) balance_wei = w3.eth.get_balance(address) # 转换为 ETH(1 ETH = 10^18 Wei) balance_eth = w3.from_wei(balance_wei, 'ether') return f"地址余额: {balance_eth} ETH" # 使用示例 address = "0x742d35Cc6634C0532925a3b844Bc454e4438f44e" print(check_eth_balance(address)) 3.2 创建新钱包 from eth_account import Account import secrets def create_new_wallet(): # 生成随机私钥 private_key = secrets.token_hex(32) account = Account.from_key(private_key) return { "address": account.address, "private_key": private_key } # 使用示例 wallet = create_new_wallet() print(f"钱包地址: {wallet['address']}") print(f"私钥: {wallet['private_key']}") 3.3 查询区块信息 def get_block_info(block_number='latest'): # 获取区块信息 block = w3.eth.get_block(block_number) info = { "区块号": block.number, "时间戳": block.timestamp, "交易数量": len(block.transactions), "矿工地址": block.miner, "难度": block.difficulty } return info # 使用示例 print(get_block_info()) 4. 实用工具函数 🛠️ 4.1 单位转换 # Wei 转换为 ETH wei_amount = 1000000000000000000 # 1 ETH eth_amount = w3.from_wei(wei_amount, 'ether') print(f"{wei_amount} Wei = {eth_amount} ETH") # ETH 转换为 Wei eth_amount = 2.5 wei_amount = w3.to_wei(eth_amount, 'ether') print(f"{eth_amount} ETH = {wei_amount} Wei") 4.2 地址验证 def is_valid_address(address): """验证以太坊地址是否有效""" return w3.is_address(address) # 使用示例 address = "0x742d35Cc6634C0532925a3b844Bc454e4438f44e" print(f"地址是否有效: {is_valid_address(address)}") 5. 监控交易示例 👀 def monitor_transactions(address, num_blocks=10): """监控指定地址的最近交易""" current_block = w3.eth.block_number for block_num in range(current_block - num_blocks, current_block + 1): block = w3.eth.get_block(block_num, full_transactions=True) for tx in block.transactions: if tx['from'].lower() == address.lower() or tx['to'].lower() == address.lower(): print(f"\n发现交易:") print(f"交易哈希: {tx['hash'].hex()}") print(f"从: {tx['from']}") print(f"到: {tx['to']}") print(f"数量: {w3.from_wei(tx['value'], 'ether')} ETH") # 使用示例 address = "0x742d35Cc6634C0532925a3b844Bc454e4438f44e" monitor_transactions(address) 6. 注意事项 ⚠️安全提示:
永远不要在代码中直接写入私钥使用环境变量存储敏感信息重要操作先在测试网络验证性能建议:
批量查询时注意请求频率适当使用缓存处理好异常情况成本考虑:
注意 gas 费用监控网络拥堵情况合理设置 gas 价格 7. 常见问题解答 ❓连接失败:
检查网络连接验证 Infura Project ID确认节点服务是否可用交易失败:
确保有足够的 ETH 支付 gas检查 nonce 值是否正确验证 gas 价格是否合理 8. 学习资源 📚官方文档:
Web3.py 文档以太坊开发者文档工具网站:
Etherscan - 交易浏览器Infura - 节点服务Remix - 在线 IDE测试网络:
GoerliSepoliaMumbai(Polygon 测试网)Web3.py入门笔记由讯客互联互联网栏目发布,感谢您对讯客互联的认可,以及对我们原创作品以及文章的青睐,非常欢迎各位朋友分享到个人网站或者朋友圈,但转载请说明文章出处“Web3.py入门笔记”