Last active
July 6, 2021 15:11
-
-
Save dipu-bd/1fff71180f4132432d0b3429b3f3a13b to your computer and use it in GitHub Desktop.
Google fonts downloader script in python
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python3 | |
import os | |
import re | |
from requests import Session | |
from urllib.parse import urlparse, parse_qs, quote_plus | |
from argparse import ArgumentParser | |
src_url_matcher = re.compile(r'''url\(["']?([^"')]+)["']?\)''') | |
sess = Session() | |
sess.headers['User-Agent'] = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36' | |
def download_family(family: str): | |
name = family.split(':')[0] | |
font_url = 'https://fonts.googleapis.com/css2?family=%s&display=swap' % family | |
print('Downloading', font_url) | |
resp = sess.get(font_url) | |
resp.raise_for_status() | |
css = resp.text | |
src_urls = {} | |
def find_url(m): | |
src = m.group(1) | |
dst = urlparse(src).path | |
src_urls[src] = dst[1:] | |
return 'url(%s)' % dst | |
css = src_url_matcher.sub(find_url, css) | |
for src, dst in src_urls.items(): | |
print('Downloading', src) | |
resp = sess.get(src) | |
resp.raise_for_status() | |
os.makedirs(os.path.dirname(dst), exist_ok=True) | |
with open(dst, mode='wb', encoding=resp.encoding) as f: | |
f.write(resp.content) | |
css_file = os.path.join('fonts', quote_plus(name + '.css')) | |
os.makedirs(os.path.dirname(css_file), exist_ok=True) | |
with open(css_file, mode='w') as f: | |
f.write(css) | |
print('<link href="/%s" rel="stylesheet">' % css_file) | |
def main(): | |
parser = ArgumentParser() | |
parser.add_argument('url', type=str, help='A google font url') | |
parser.add_argument('-t', '--target', type=str, help='Target directory') | |
args = parser.parse_args() | |
if args.target: | |
os.makedirs(args.target, exist_ok=True) | |
os.chdir(args.target) | |
font_url: str = args.url | |
if not font_url.startswith('https://fonts.googleapis.com/'): | |
raise Exception('Only google fonts are supported') | |
query = parse_qs(urlparse(font_url).query) | |
for family in query['family']: | |
download_family(family) | |
print() | |
if __name__ == '__main__': | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment