How to change values of url query in python?

Here is a simple example:

def patch_url(url, **kwargs):
    from urllib.parse import urlparse, urlencode, parse_qsl
    return urlparse(url)._replace(query=urlencode(
        dict(parse_qsl(urlparse(url).query), **kwargs))).geturl()


assert patch_url("https://httpbin.org/get?hello=world", hello="human") \
       == "https://httpbin.org/get?hello=human"

You can use the package furl.

from furl import furl

url = furl("http://www.example.com?type=a&type1=b&type2=c")
url.set({"type": "a'or '1'='1'"})
url.url

gives the output: http://www.example.com?type=a%27or+%271%27%3D%271%27

and decoded: http://www.example.com?type=a'or '1'='1'


In Python2.x

You can use urlparse.urlparse function and ParseResult._replace method:

import urlparse
url = "http://www.example.com?type=a&type1=b&type2=c"
trigger = ["'or '1'='1'"," 'OR '1'='2'","'OR a=a"]

parsed = urlparse.urlparse(url)
querys = parsed.query.split("&")
result = []
for pairs in trigger:
    new_query = "&".join([ "{}{}".format(query, pairs) for query in querys])
    parsed = parsed._replace(query=new_query)
    result.append(urlparse.urlunparse(parsed))

Note

The urlparse module is renamed to urllib.parse in Python 3. The 2to3 tool will automatically adapt imports when converting your sources to Python 3.

In Python3.x

You can use urlparse.urlparse function as well.

import urllib.parse as urlparse
url = "http://www.example.com?type=a&type1=b&type2=c"
trigger = ["'or '1'='1'"," 'OR '1'='2'","'OR a=a"]

parsed = urlparse.urlparse(url)
querys = parsed.query.split("&")
result = []
for pairs in trigger:
    new_query = "&".join([ "{}{}".format(query, pairs) for query in querys])
    parsed = parsed._replace(query=new_query)
    result.append(urlparse.urlunparse(parsed))

DEMO OUTPUT:

["http://www.example.com?type=a'or '1'='1'&type1=b'or '1'='1'&type2=c'or '1'='1'", "http://www.example.com?type=a 'OR '1'='2'&type1=b 'OR '1'='2'&type2=c 'OR '1'='2'", "http://www.example.com?type=a'OR a=a&type1=b'OR a=a&type2=c'OR a=a"]