如何更改网址的参数值?没有正则表达式。
现在我尝试一下,但是很长:
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}'
此外,我尝试通过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)
但是在
urlparsed.query = query_new
上会出现错误AttributeError: can't set attribute
。 最佳答案
元组是不可变的,因此您必须将其替换。此处_是为了避免与字段名._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())