Skip to content

Instantly share code, notes, and snippets.

@iomarmochtar
Created January 15, 2019 02:49
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 iomarmochtar/9fc64d3d200df2768c3147c4206f9eb3 to your computer and use it in GitHub Desktop.
Save iomarmochtar/9fc64d3d200df2768c3147c4206f9eb3 to your computer and use it in GitHub Desktop.
Python script to download google fonts
__author__ = ('Imam Omar Mochtar', 'iomarmochtar@gmail.com')
import urllib2
import sys
import os
import re
FONTS_DIR = 'fonts'
CSS_FILE = 'offline.css'
site = sys.argv[1]
url_re = re.compile(r'url\((.*?)\)')
USER_AGENT = 'Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:64.0) Gecko/20100101 Firefox/64.0'
for check in [FONTS_DIR, CSS_FILE]:
if os.path.isdir(check) or os.path.isfile(check):
print('directory/file {} is already exist please do backup or remove it'.format(check))
sys.exit(1)
os.mkdir(FONTS_DIR)
fetcher = urllib2.build_opener()
fetcher.addheaders = [('User-Agent', USER_AGENT)]
font_urls = []
css_code = []
for line in fetcher.open(site).readlines():
url_match = url_re.search(line)
if url_match:
font_url = url_match.group(1)
font_urls.append(font_url)
font_path = os.path.join(
'..', FONTS_DIR, os.path.basename(font_url)
)
# subtitute url in css line
line = url_re.sub(
'url({})'.format(font_path)
, line)
css_code.append(line)
for url in font_urls:
print('Downloading {}'.format(url))
local_path = os.path.join(
FONTS_DIR, os.path.basename(url))
with open(local_path, 'wb') as fp:
fetch = urllib2.urlopen(url)
fp.write(
fetcher.open(url).read())
with open(CSS_FILE, 'w') as fp:
print('Writing css file {}'.format(CSS_FILE))
fp.writelines(css_code)
print('DONE')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment