Last active
March 8, 2025 14:21
-
-
Save h0tw1r3/f0c1e6295084f65aeb448af9cc61b358 to your computer and use it in GitHub Desktop.
Fix openscap report, externalize all inline scripts and stylesheets
This file contains 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 | |
# * finds all inline style and script elements in an html file | |
# exports the code into a file (ie. filename.css, filename.js) | |
# removes the original tag from the html | |
# * replaces inline styles and scripts with tags in the header | |
# sourcing the new external code | |
# disable tracebacks | |
import sys | |
sys.tracebacklimit = 0 | |
import os | |
from lxml import html | |
if len(sys.argv) < 3: | |
print("two arguments required, path to html file and output directory", file=sys.stderr) | |
raise SystemExit(1) | |
try: | |
os.mkdir(sys.argv[2]) | |
except FileExistsError: | |
pass | |
output_fn = os.path.join(sys.argv[2], os.path.basename(sys.argv[1])) | |
output_base_fn, _ = os.path.splitext(output_fn) | |
fp = { 'style': None, 'script': None } | |
tree = html.parse(sys.argv[1]) | |
root = tree.getroot() | |
for el in root.xpath('.//style | .//script'): | |
if not fp[el.tag]: | |
ext = 'css' if (el.tag == 'style') else 'js' | |
fp[el.tag] = open(f'{output_base_fn}.{ext}', 'w') | |
fp[el.tag].write(el.text_content()) | |
fp[el.tag].write("\n") | |
el.drop_tree() | |
head = root.find('.//head') | |
if fp['script']: | |
script_tag = html.Element('script') | |
script_tag.set('type', 'text/javascript') | |
script_tag.set('src', os.path.basename(fp['script'].name)) | |
head.append(script_tag) | |
if fp['style']: | |
link_tag = html.Element('link') | |
link_tag.set('rel', 'stylesheet') | |
link_tag.set('href', os.path.basename(fp['style'].name)) | |
link_tag.set('type', 'text/css') | |
link_tag.set('media', 'screen') | |
head.append(link_tag) | |
tree.write(output_fn, encoding='utf-8', method='html') |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment