Last active
July 10, 2023 08:52
-
-
Save Brawn1/b423d695b2d54c274822be657192c90f to your computer and use it in GitHub Desktop.
Download all Links from Google Font File
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
import requests | |
import cssutils | |
from pathlib import Path | |
import os | |
from typing import Union | |
class CSSDownloader: | |
def __init__(self, fontdir: str = "./fonts/", baseurl: str = 'https://fonts.gstatic.com/'): | |
self.dlurls = list() | |
self.baseurl = baseurl | |
self.fontdir = fontdir | |
@staticmethod | |
def cleanup_srcstring(item: str) -> str: | |
return item.split(' format')[0].replace('url(', '').replace(')', '') | |
def gen_dllist(self, cssfile: 'Path'): | |
fontfile = cssutils.parseFile(cssfile) | |
for rule in fontfile: | |
try: | |
self.dlurls.append(self.cleanup_srcstring(item=rule.style.src)) | |
except AttributeError: | |
continue | |
def _path_fromurl(self, url: str, baseurl: str = None, autogendirs: bool = True) -> 'Path': | |
if baseurl and self.baseurl != baseurl: | |
self.baseurl = baseurl | |
exturl = url.replace(self.baseurl, '') | |
filepath = Path(exturl) | |
if autogendirs and not filepath.parent.exists(): | |
filepath.parent.mkdir(parents=True, exist_ok=True) | |
return filepath | |
def _save_content(self, content: Union[str, bytes], filepath: 'Path') -> bool: | |
is_written = False | |
if isinstance(content, str): | |
content = content.encode('utf-8') | |
with open(filepath, "wb") as f: | |
f.write(content) | |
is_written = True | |
return is_written | |
def _download(self, url: str): | |
resp = requests.get(url, timeout=10) | |
if resp.ok: | |
return resp.content | |
def create_files(self, cssfile: str): | |
cssfile = Path(cssfile) | |
self.gen_dllist(cssfile=cssfile) | |
for url in self.dlurls: | |
print(f"download woff from {url}") | |
content = self._download(url=url) | |
if content: | |
filepath = self._path_fromurl(url=url) | |
self._save_content(content=content, filepath=filepath) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Requirements:
Usage: