You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python中Web3开发报错:byte indices must be integers or slices, not str

问题解决:byte indices must be integers or slices, not str

核心问题分析

报错的根本原因有两个:

  1. tx不是字典类型:你拿到的tx是字节流(bytes)格式,而非解析后的交易字典,用字符串键'from'索引自然触发类型错误。
  2. Excel列的判断逻辑错误:ws['A']返回的是A列的单元格对象集合,不是存储的地址字符串列表,直接用in判断会失效。

修复步骤

1. 确保tx是解析后的字典

如果transactions是Web3原始RPC调用返回的字节数据,先通过解码转为字典:

from web3 import Web3

for tx_bytes in transactions:
    # 将字节格式的交易数据解析为字典
    tx = w3.eth.decode_transaction(tx_bytes)
    # 后续逻辑...

如果transactions是通过w3.eth.get_transactions()这类方法获取的,本身已是字典,检查是否在之前代码中误将tx转为了字节类型。

2. 修复Excel地址存在性判断

先提取A列已有的地址为字符串列表,再做判断:

# 提前提取A列所有非空单元格的地址值
existing_addresses = [cell.value.lower() for cell in ws['A'] if cell.value is not None]

for tx in transactions:
    # 先确保tx是字典格式
    tx = w3.eth.decode_transaction(tx) if isinstance(tx, bytes) else tx
    sender_addr = tx['from'].lower()
    
    if sender_addr not in existing_addresses:
        contract = w3.eth.contract(address=tx['to'], abi=CONTRACT_ABI)
        contract.functions.yourFunction().transact()
        
        ws.append([sender_addr])
        # 更新列表,避免重复判断
        existing_addresses.append(sender_addr)

3. 额外注意事项

  • Web3返回的地址有小写或校验和格式两种,统一转小写可避免格式不一致导致的判断失误。
  • 批量处理时,提前解析所有交易并提取地址,能提升整体处理效率。

内容的提问来源于stack exchange,提问作者muttynhg

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.10 00:40:22