Change a url parameter
Asked Answered
F

3

11

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.

Flexuous answered 17/6, 2018 at 3:9 Comment(3)
Hi @bl79, can you provide an example url and the results you are trying to achieve?Copernicus
Hi, I added an example url. I want change page=1 to page=2.Flexuous
Try requests docs.python-requests.org/en/master is pretty simpleHinojosa
S
10

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())
Syphilology answered 17/6, 2018 at 3:47 Comment(0)
T
7

Just using urllib for python 3 (quite long but flexible):

from urllib.parse import urlparse, ParseResult, parse_qs, urlencode

u = urlparse('http://example.com/?page=1&text=test#section')
params = parse_qs(u.query)
params['page'] = 22  #  change query param here
res = ParseResult(scheme=u.scheme, netloc=u.hostname, path=u.path, params=u.params, query=urlencode(params), fragment=u.fragment)
print (res.geturl())
Thespian answered 12/7, 2019 at 13:2 Comment(0)
D
0

As namedtuple are immutable, we have to work around.

A solution is to use a very basic and fast replace.

from urllib.parse import urlparse, parse_qs, urlencode

url = 'http://example.com/?page=1&text=test#section'

parsed_url = urlparse(url)
params = parse_qs(parsed_url.query)
params['page'] = 22  #  changing query parameters

new_url = url.replace(parsed_url.query, urlencode(params))
Denounce answered 29/11, 2022 at 16:54 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.