Python中Web3开发报错:byte indices must be integers or slices, not str
问题解决:byte indices must be integers or slices, not str
核心问题分析
报错的根本原因有两个:
tx不是字典类型:你拿到的tx是字节流(bytes)格式,而非解析后的交易字典,用字符串键'from'索引自然触发类型错误。- 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
相关产品推荐
相关产品推荐

