How do I remove a query string from URL using Python How do I remove a query string from URL using Python python python

How do I remove a query string from URL using Python


import sysif sys.version_info.major == 3:    from urllib.parse import urlencode, urlparse, urlunparse, parse_qselse:    from urllib import urlencode    from urlparse import urlparse, urlunparse, parse_qsurl = 'http://example.com/?a=text&q2=text2&q3=text3&q2=text4&b#q2=keep_fragment'u = urlparse(url)query = parse_qs(u.query, keep_blank_values=True)query.pop('q2', None)u = u._replace(query=urlencode(query, True))print(urlunparse(u))

Output:

http://example.com/?a=text&q3=text3&b=#q2=keep_fragment


To remove all query string parameters:

from urllib.parse import urljoin, urlparseurl = 'http://example.com/?a=text&q2=text2&q3=text3&q2=text4'urljoin(url, urlparse(url).path)  # 'http://example.com/'

For Python2, replace the import with:

from urlparse import urljoin, urlparse


Isn't this just a matter of splitting a string on a character?

>>> url = http://example.com/?a=text&q2=text2&q3=text3&q2=text4>>> url = url.split('?')[0]'http://example.com/'