#!/usr/bin/env python3 """Urlparse — URL parser, encoder, and parameter extractor.""" import argparse, sys, urllib.parse, json def color(text, code): return f"\033[{code}m{text}\033[0m" if sys.stdout.isatty() else text def cmd_parse(args): for url in args.urls: parsed = urllib.parse.urlparse(url) params = urllib.parse.parse_qs(parsed.query) print(f"\n {color('URL:', '36;1')} {url}") print(f" {color('─' * 50, '90')}") print(f" Scheme: {color(parsed.scheme, '32')}") print(f" Netloc: {parsed.netloc}") print(f" Path: {parsed.path}") print(f" Params: {parsed.params or '(none)'}") print(f" Query: {parsed.query or '(none)'}") print(f" Fragment: {parsed.fragment or '(none)'}") if params and parsed.query: print(f"\n {color('Query Parameters:', '33')}") for key, values in params.items(): for val in values: print(f" {color(key, '36')} = {val}") print() def cmd_encode(args): text = " ".join(args.text) encoded = urllib.parse.quote(text) print(encoded) def cmd_decode(args): text = " ".join(args.text) decoded = urllib.parse.unquote(text) print(decoded) def cmd_extract(args): for url in args.urls: parsed = urllib.parse.urlparse(url) params = urllib.parse.parse_qs(parsed.query) print(json.dumps({ "url": url, "scheme": parsed.scheme, "host": parsed.netloc, "path": parsed.path, "query": parsed.query, "fragment": parsed.fragment, "params": {k: v[0] if len(v) == 1 else v for k, v in params.items()}, }, indent=2)) def main(): parser = argparse.ArgumentParser( description="Urlparse — URL parser, encoder, and parameter extractor", formatter_class=argparse.RawDescriptionHelpFormatter, epilog=( "Examples:\n" " urlparse parse 'https://example.com/path?q=test&page=1'\n" " urlparse encode 'hello world & more'\n" " urlparse decode 'hello+world'\n" " urlparse extract 'https://example.com?a=1&b=2' # JSON output\n" ), ) parser.add_argument("--version", action="version", version="urlparse 1.0.0") sub = parser.add_subparsers(dest="command", required=True) p = sub.add_parser("parse", help="Parse and display URL components") p.add_argument("urls", nargs="+", help="URLs to parse") e = sub.add_parser("encode", help="URL-encode text") e.add_argument("text", nargs="+", help="Text to encode") d = sub.add_parser("decode", help="URL-decode text") d.add_argument("text", nargs="+", help="Text to decode") x = sub.add_parser("extract", help="Extract parameters as JSON") x.add_argument("urls", nargs="+", help="URLs to parse") args = parser.parse_args() if args.command == "parse": cmd_parse(args) elif args.command == "encode": cmd_encode(args) elif args.command == "decode": cmd_decode(args) elif args.command == "extract": cmd_extract(args) if __name__ == "__main__": main()