add support for css and making relative links absolute

This commit is contained in:
askiiart 2025-01-04 17:19:32 -06:00
parent 93f6b400f4
commit c541151dff
Signed by untrusted user who does not match committer: askiiart
GPG key ID: 6A32977DAF31746A
2 changed files with 24 additions and 4 deletions

View file

@ -4,12 +4,15 @@ With "liberty" and JS for none.
---
It's a thing to make a webpage into a single file with no external dependencies, with, of course, "liberty" (no options) and JS for none (it doesn't do JS).
This makes any page a portable, single file with no external dependencies - with, of course, "liberty" (no options) and JS for none (it doesn't do JS).
Currently it supports hardcoding:
- favicons
- images
- CSS
And also fixes any relative links to be absolute.
## Usage
@ -23,5 +26,4 @@ OWUG is licensed under `GPL-3.0-only`.
## TODO
- Add CSS support
- Add support for making relative links into absolute ones (`/.a.html` -> `https://example.com/a.html`)
- Add font support

20
owug.py
View file

@ -29,7 +29,7 @@ soup = BeautifulSoup(html, 'html5lib')
# hardcode favicon
favicons = soup.find_all('link', rel='icon')
for favicon in favicons:
if favicon.attrs['rel'].count('icon') > 0:
if 'icon' in favicon.attrs['rel']:
url = absolute_url(favicon.attrs['href'], domain_thing)
mime_type = requests.head(url).headers['Content-Type']
@ -47,5 +47,23 @@ for item in imgs:
new_url = f'data:{mime_type};base64,{as_base64}'
item.attrs['src'] = new_url
# hardcode css
# note: not sure it matters, but this puts the CSS in <head>
head = soup.find_all('link', rel='stylesheet')
for item in head:
url = absolute_url(item.attrs['href'], domain_thing)
style_data = requests.get(url).content.decode()
head = soup.find('head')
new_tag = soup.new_tag('style')
new_tag.string = style_data
soup.head.append(new_tag)
item.decompose()
# change relative links to absolute
links = soup.find_all('link')
for item in links:
if 'icon' not in item.attrs['rel']:
item.attrs['href'] = absolute_url(item.attrs['href'], domain_thing)
with open(sys.argv[2], 'wt') as f:
f.write(str(soup))