Inspect a URL without visiting it
Find the actual URL host and validate the parts your analysis depends on.
Read the authority, not the familiar text
In https://trusted.example@capture.example.test/login, the host is capture.example.test. The familiar name before @ is user information. Searching a URL for an allowlisted string can therefore produce the wrong conclusion. urllib.parse.urlsplit() exposes the components separately.
Use .hostname for the host and .port for the parsed port. Accessing .port can raise ValueError for invalid text or an out-of-range number. A missing port is different from an explicit zero; test for None when choosing a default.
Parsing is not a safety verdict
Python's URL parser is deliberately permissive. This exercise adds a small, documented policy: absolute HTTP or HTTPS URLs only, a host must be present, and whitespace or control characters are rejected before parsing. This avoids silently accepting characters that a parser may remove.
The report records whether user information is present without copying a possible password. It does not fetch the address, resolve DNS, or decide that a host is trustworthy. International domain registration and public-suffix analysis are separate topics; these fixtures use ASCII hostnames and documentation IP addresses.
Preserve the original URL in source evidence and use normalized components for comparison. Do not percent-decode a complete URL and then treat it as the original structure: decoding separators can change what you think you are inspecting.
from urllib.parse import urlsplit
parts = urlsplit("https://trusted.example@capture.example.test:8443/login")
print(parts.hostname, parts.port, parts.username is not None)
Put it into practice.
Define inspect_url(value). Reject empty/non-string input, whitespace/control characters (codepoints <= 32 or 127), non-HTTP(S) schemes, absent hosts, and invalid ports with ValueError. Return scheme, host (lowercase without trailing dots), port (explicit port or 80/443), and has_userinfo (boolean). Support bracketed IPv6. Do not make network requests or expose userinfo values.
See an explained solution
from urllib.parse import urlsplit
def inspect_url(value):
if not isinstance(value, str) or not value or any(ord(c) < 33 or ord(c) == 127 for c in value):
raise ValueError("URL contains whitespace or controls")
try:
parts = urlsplit(value)
port = parts.port
if parts.scheme not in ("http", "https") or not parts.hostname:
raise ValueError("Need an absolute HTTP(S) URL")
except ValueError as error:
raise ValueError("Invalid URL") from error
return {"scheme": parts.scheme, "host": parts.hostname.lower().rstrip("."), "port": port if port is not None else (443 if parts.scheme == "https" else 80), "has_userinfo": parts.username is not None or parts.password is not None}
The parser separates the real host from credentials and path text. Explicit validation supplies the policy the parser intentionally does not impose.