Skip to content

Instantly share code, notes, and snippets.

@ant4g0nist
Created August 11, 2021 14:40
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ant4g0nist/273963399a5ed342785d711ceed39a98 to your computer and use it in GitHub Desktop.
Save ant4g0nist/273963399a5ed342785d711ceed39a98 to your computer and use it in GitHub Desktop.
Downloads Contract Code from etherscan.io (works for all *nets) given the deployed url.
#!/usr/bin/env python3
# Usage: ./contractDownloader.py -u https://etherscan.io/address/0x0f51bb10119727a7e5ea3538074fb341f56b09ad#code
# Usage: ./contractDownloader.py -u https://kovan.etherscan.io/address/0x7b6b10caa9e8e9552ba72638ea5b47c25afea1f3#code
import os
import bs4
import sys
import argparse
import requests
headers = {"User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10.15; rv:86.0) Gecko/20100101 Firefox/86.0"}
def getAddressAndUrl(url):
contractAddress = url.split("/")[-1][:42]
if "etherscan.io/token/" in url.lower():
return contractAddress, url.lower().replace('etherscan.io/token/', 'etherscan.io/address/')
return contractAddress, url
def fetchEtherScanCodePage(contractAddress, url):
res = requests.get(url, headers=headers)
soup = bs4.BeautifulSoup(res.text, features="html.parser")
pre = soup.find("pre", {"id":"js-copytextarea2"})
filenames = []
for source in soup.select('[id^="panel-sourcecode"]'):
span = source.parent.parent.next
filename = span.text
if "File " in filename:
filename = filename.split(":")[-1].strip(" ")
filenames.append(filename)
try:
os.mkdir(f"./{contractAddress}")
except:
pass
i = 0
for source in soup.select('[id^="editor"]'):
filename = filenames[i]
print(f"Downloading ./{contractAddress}/{filename}...")
with open(f'./{contractAddress}/{filename}','w') as f:
f.write(source.text)
i+=1
if __name__ == "__main__":
parser = argparse.ArgumentParser("Etherscan Contract Code downloader...")
parser.add_argument("-u","--url", required=True, help="Etherscan URL for contract")
args = parser.parse_args()
contractAddress, url = getAddressAndUrl(args.url)
fetchEtherScanCodePage(contractAddress, url)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment