如何使用python替换url参数


import urllib.parse as urlparse
url = "http://www.example.com?type=aaaaaaa&type1=bbbbbbb&type2=cccccccc"
trigger = ["value1","value2","value3"]
parsed = urlparse.urlparse(url)
querys = parsed.query.split("&")
result = []
for pairs in trigger:
new_query = "&".join([ "{}{}".format(query, pairs) for query in querys])
parsed = parsed._replace(query=new_query)
result.append(urlparse.urlunparse(parsed))
print(result)

如何通过替换查询参数值来返回URL列表?

输出结果:

["http://www.example.com?type=aaaaavalue1&type1=bbbbbbvalue1&type2=ccccccccvalue1", "http://www.example.com?type=aaaaavalue2&type1=bbbbbbvalue2&type2=ccccccccvalue2", "http://www.example.com?type=aaaaavalue3&type1=bbbbbbvalue3&type2=ccccccccvalue3"]

预期结果:

["http://www.example.com?type=value1&type1=value1&type2=value1", "http://www.example.com?type=value2&type1=value2&type2=value2", "http://www.example.com?type=value3&type1=value3&type2=value3"]

我只想用自定义参数值替换URL参数值,不想附加它们。

您可以使用函数replace

url = "http://www.example.com?type=aaaaaaa&type1=bbbbbbb&type2=cccccccc"
trigger = []
for i in range(url.count("=")):
trigger.append("value{}".format(i+1))
urls = []
start = [pos for pos, char in enumerate(url) if char == "="]
end   = [pos for pos, char in enumerate(url) if char == "&"]
end.append(len(url))
for i in range(len(trigger)):
urls.append(url.replace(url[start[0]+1:end[0]],trigger[i]).replace(url[start[1]+1:end[1]],trigger[i]).replace(url[start[2]+1:end[2]],trigger[i]))

>>> urls
['http://www.example.com?type=value1&type1=value1&type2=value1',
'http://www.example.com?type=value2&type1=value2&type2=value2',
'http://www.example.com?type=value3&type1=value3&type2=value3']

相关内容

  • 没有找到相关文章

最新更新