Python script to retrieve all ERC-20 token and NFT balances for a wallet address using web3.py

I’m working on a Python project where I need to fetch all token balances for any given wallet address. Right now I can only get ETH balance but I want to see all ERC-20 tokens and NFTs that belong to a specific address.

I want to create a function that takes a wallet address as input and returns the total value of all tokens plus NFTs. I’ve been struggling with this for a while and keep getting stuck at just the main ETH balance.

Can someone help me write a complete solution that will scan through all tokens associated with an address and display the results? I’m using the web3.py library for this project.

You can’t just call balance methods directly - you need to query blockchain events instead. For ERC-20 tokens, scan Transfer events where your address shows up as sender or recipient. This builds a list of token contracts you’ve used, then call balanceOf() on each one. Same deal for NFTs, but look for ERC-721 and ERC-1155 Transfer events. The tricky part is there’s no master registry of all tokens, so you’re basically rebuilding your transaction history from scratch. I’d recommend using Alchemy or Infura APIs rather than pure web3.py - they’ve got optimized endpoints built for exactly this. The blockchain scanning method works but gets really slow if your address has tons of activity.

hey, totally get the struggle! try using web3’s erc20 methods; they should help with fetching those balances. also, etherscan’s api might be a lifesaver too. hope that points you in the right direction!