If you're looking to create a Python script to clean URLs, one common task is to remove tracking parameters and unnecessary parts of a URL to obtain a clean, canonical version. Here’s a basic example of how you might achieve this using Python. This script will:
Parse the URLs.
Remove common tracking parameters.
Reconstruct the cleaned URL.
We’ll use Python’s urlparse and urlunparse from the urllib.parse module to handle the URLs, and parse_qs and urlencode to manage query parameters.
Here is a sample code for a simple link cleaner:
python
from urllib.parse import urlparse, urlunparse, parse_qsl, urlencode
def clean_url(url):
# Parse the URL into its components
parsed_url = urlparse(url)
# Convert query string into a dictionary and make a mutable copy
query_params = dict(parse_qsl(parsed_url.query))
# Define common tracking parameters to remove
tracking_params = ["utm_source", "utm_medium", "utm_campaign", "utm_term", "utm_content", "fbclid", "gclid", "ref"]
# Remove tracking parameters from the query dictionary
clean_query_params = {k: v for k, v in query_params.items() if k not in tracking_params}
# Rebuild the URL without tracking parameters
cleaned_url = urlunparse((
parsed_url.scheme,
parsed_url.netloc,
parsed_url.path,
parsed_url.params,
urlencode(clean_query_params, doseq=True), # Re-encode the cleaned query dictionary
parsed_url.fragment
))
return cleaned_url
# Example usage
url = "https://www.example.com/page?utm_source=newsletter&utm_medium=email&id=123&ref=homepage"
cleaned_url = clean_url(url)
print(cleaned_url)
Explanation
Parsing the URL: The script uses urlparse to separate the URL into components like scheme, netloc, path, and query.
Query Parameters Handling: parse_qsl turns the query string into a list of key-value pairs, which is then converted to a dictionary.
Removing Tracking Parameters: You define a list of common tracking parameters to remove. These keys are stripped from the query parameter dictionary.
Rebuilding the URL: Using urlunparse, the URL is reconstructed without the removed tracking parameters.
This script can be used as a basis for building more sophisticated link cleaning tools, adding additional logic as needed to handle other types of URL parameters or apply more complex cleaning rules.