python with_version.py input.html v=0.0.1 output.html
import bs4 import sys def param_merge(vstr, pstr): vsplit = vstr.split('=') pdict = {} for pkey in pstr.split('&'): psplit = pkey.split('=') pdict[psplit[0]] = psplit[1] pdict[vsplit[0]] = vsplit[1] pstr2_list = [k + '=' + pdict[k] for k in pdict] return pstr2_list def main(): if len(sys.argv) == 1 or (len(sys.argv) > 1 and sys.argv[1] == '--help'): print("""usage: python with_version.py input.html v=0.0.1 output.html""") return elif len(sys.argv) != 4: return html = sys.argv[1] vstr = sys.argv[2] output_html = sys.argv[3] # load the file with open(html, 'r', encoding='utf-8') as inf: txt = inf.read() soup = bs4.BeautifulSoup(txt, 'html.parser') for script in soup.find_all("script", recursive=True): src = script['src'] if -1 == src.find('?'): script['src'] = src + '?' + vstr else: [src, pstr] = src.split('?') merged = param_merge(vstr, pstr) script['src'] = src + '?' + '&'.join(merged) for link in soup.find_all("link", recursive=True): href = link['href'] if -1 == href.find('?'): link['href'] = href + '?' + vstr else: [href, pstr] = href.split('?') merged = param_merge(vstr, pstr) link['href'] = href + '?' + '&'.join(merged) # save the file again with open(output_html, "w", encoding='utf-8') as fout: fout.write(soup.prettify()) if __name__ == '__main__': main()