Remove utm_* parameters from URL in Python

Viewed 3545

I've been trying to remove all utm_* parameters from a list of URLs. The closest thing I have found is this: https://gist.github.com/626834.

Any ideas?

5 Answers

How about this. Nice and simple:

url = 'https://searchengineland.com/amazon-q3-ad-revenues-surpass-1-billion-roughly-2x-early-2016-285763?utm_source=feedburner&utm_medium=feed&utm_campaign=feed-main'

print url[:url.find('?utm')]

https://searchengineland.com/amazon-q3-ad-revenues-surpass-1-billion-roughly-2x-early-2016-285763

Using regex

import re
def clean_url(url):
    return re.sub(r'(?<=[?&])utm_[^&]+&?', '', url)

What's going on? We are using regular expressions to find all instances of strings that look like utm_somekey=somevalue which is preceded by either "?" or "&".

Testing it:

tests = [   "http://localhost/index.php?a=1&utm_source=1&b=2",
            "http://localhost/index.php?a=1&utm_source=1&b=2#hash",
            "http://localhost/index.php?a=1&utm_source=1&b=2&utm_something=no#hash",
            "http://localhost/index.php?a=1&utm_source=1&utm_a=yes&b=2#hash",
            "http://localhost/index.php?utm_a=a",
            "http://localhost/index.php?a=utm_a",
            "http://localhost/index.php?a=1&b=2",
            "http://localhost/index.php",
            "http://localhost/index.php#hash2"
        ]

for t in tests:
    print(clean_url(t))

http://localhost/index.php?a=1&b=2
http://localhost/index.php?a=1&b=2#hash
http://localhost/index.php?a=1&b=2&
http://localhost/index.php?a=1&b=2#hash
http://localhost/index.php?
http://localhost/index.php?a=utm_a
http://localhost/index.php?a=1&b=2
http://localhost/index.php
http://localhost/index.php#hash2
Related