Skip to content

Instantly share code, notes, and snippets.

@russhughes
Last active May 8, 2023 14:56
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save russhughes/31b14f468872cc53d08087bd496ceceb to your computer and use it in GitHub Desktop.
Save russhughes/31b14f468872cc53d08087bd496ceceb to your computer and use it in GitHub Desktop.
#!/usr/bin/env python3
"""
Download the first firmware from the webpage
requirements:
requests
bs4
lxml
Install requirements if not installed:
pip3 install requests bs4 lxml
Example use:
./download_firmware.py https://micropython.org/download/seeed_xiao_nrf52/ uf2
"""
import argparse
import requests
from bs4 import BeautifulSoup
def get_firmware_links(url, extension="uf2"):
"""get all href links that end with the given extension"""
# create response object
request = requests.get(url)
# create beautiful-soup object
soup = BeautifulSoup(request.content, features="lxml")
# find all links on web-page ending with .extension
links = soup.findAll("a")
return [
url + link["href"] for link in links if link["href"].endswith(f".{extension}")
]
def download_firmware(links):
"""iterate through all links in firmware_links and download the first link"""
for link in links:
# obtain filename by splitting url and getting last string
file_name = link.split("/")[-1]
print(f"Downloading file:{file_name}")
# create response object
request = requests.get(link, stream=True)
# download started
with open(file_name, "wb") as f:
for chunk in request.iter_content(chunk_size=1024 * 1024):
if chunk:
f.write(chunk)
print(f"{file_name} downloaded!\n")
# break after first firmware is downloaded or remove break to download all
break
if __name__ == "__main__":
argparser = argparse.ArgumentParser(
prog="download_firmware.py",
description="Download the first firmware link from the webpage",
epilog="Example: ./download_firmware.py https://micropython.org/download/seeed_xiao_nrf52/ uf2",
)
argparser.add_argument("url", help="URL of the firmware page to download")
argparser.add_argument("extension", help="Extension of the firmware to download")
args = argparser.parse_args()
firmware_links = get_firmware_links(args.url)
download_firmware(firmware_links)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment