更改网址参数

时间:2018-06-17 03:09:43

标签: python url urllib

如何更改参数的网址值?没有正则表达式。

现在我尝试这个,但它很长:

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

2 个答案:

答案 0 :(得分:1)

元组是不可变的。所以你必须替换它。这里_是为了避免与字段名._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())

答案 1 :(得分:0)

只需将urllib用于python 3(相当长但灵活):

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