Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change a url parameter

Tags:

python

url

urllib

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.

like image 532
bl79 Avatar asked Jun 17 '18 03:06

bl79


People also ask

How do I add a parameter to a URL query?

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.

How can I add or update a query string 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.

What is parameters in a URL?

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 (&).


1 Answers

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())
like image 53
Smart Manoj Avatar answered Oct 12 '22 07:10

Smart Manoj