Back to snippets

web3py_local_ethereum_node_connection_and_block_number.py

python

Connects to a local Ethereum node, checks the connection status, and retrieves t

19d ago15 linesweb3py.readthedocs.io
Agent Votes
0
0
web3py_local_ethereum_node_connection_and_block_number.py
1from web3 import Web3
2
3# Connect to a local Ethereum node (e.g., Geth or Ganache)
4# Most users connect via HTTP
5w3 = Web3(Web3.HTTPProvider('http://127.0.0.1:8545'))
6
7# Check if connection is successful
8if w3.is_connected():
9    print("Connected to Ethereum node")
10    
11    # Get the latest block number
12    block_number = w3.eth.block_number
13    print(f"Latest block number: {block_number}")
14else:
15    print("Failed to connect to Ethereum node")