Parsing URLs in Python
Taking URLs apart and putting query strings together.
from urllib.parse import urlparse, parse_qs, urlencode, urljoin
url = "https://typestar.io/practice?lang=python&theme=monokai"
parts = urlparse(url)
host = parts.netloc
path = parts.path
params = parse_qs(parts.query)
lang = params["lang"][0]
query = urlencode({"lang": "rust", "duration": 300})
next_url = f"{parts.scheme}://{host}{path}?{query}"
absolute = urljoin(url, "/profile")
How it works
urlparsesplits scheme, host, path, and query.parse_qsturns the query into a dict.urlencodeandurljoinrebuild URLs.
The run, in numbers
- Lines
- 12
- Characters to type
- 385
- Tokens
- 103
- Three-star pace
- 105 tpm
At the three-star pace of 105 tokens a minute, this run takes about 59 seconds.
Step 4 of 4 in Web, step 13 of 41 in Domain tools.