How change a parameter's value of url? Without regexps.
Now I try this, but it's long:
from urllib.parse import parse_qs, urlencode, urlsplit
url = 'http://example.com/?page=1&text=test#section'
param, newvalue = 'page', '2'
url, sharp, frag = url.partition('#')
base, q, query = url.partition('?')
query_dict = parse_qs(query)
query_dict[param][0] = newvalue
query_new = urlencode(query_dict, doseq=True)
url_new = f'{base}{q}{query_new}{sharp}{frag}'
Also, I tried by urlsplit:
parsed = urlsplit(url)
query_dict = parse_qs(parsed.query)
query_dict[param][0] = newvalue
query_new = urlencode(query_dict, doseq=True)
parsed.query = query_new
url_new = urlencode(parsed)
But on urlparsed.query = query_new
it rise error AttributeError: can't set attribute
.
Query parameters are a defined set of parameters attached to the end of a url. They are extensions of the URL that are used to help define specific content or actions based on the data being passed. To append query params to the end of a URL, a '? ' Is added followed immediately by a query parameter.
You can use the browser's native URL API to do this in a fairly simple way, where key and value are your parameter name and parameter value respectively. const url = new URL(location. href); url. searchParams.
URL parameter is a way to pass information about a click through its URL. You can insert URL parameters into your URLs so that your URLs track information about a click. URL parameters are made of a key and a value separated by an equals sign (=) and joined by an ampersand (&).
Tuples are immutable.So you have to replace it .Here _ is meant to avoid conflict with fieldnames ._replace
from urllib.parse import parse_qs, urlencode, urlsplit
url = 'http://example.com/?page=1&text=test#section'
param, newvalue = 'page', '2'
parsed = urlsplit(url)
query_dict = parse_qs(parsed.query)
query_dict[param][0] = newvalue
query_new = urlencode(query_dict, doseq=True)
parsed=parsed._replace(query=query_new)
url_new = (parsed.geturl())
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With