用python一次替换多个模式



所以我想做的基本上是我有一个带有多个参数的url列表,例如:

https://www.somesite.com/path/path2/path3?param1=value1&param2=value2

我想要的是这样的东西:

https://www.somesite.com/path/path2/path3?param1=PAYLOAD&param2=value2
https://www.somesite.com/path/path2/path3?param1=value1&param2=PAYLOAD

就像我想迭代每个参数(基本上是"="one_answers"&"的每个匹配(,每次替换一个值。提前谢谢。

from urllib.parse import urlparse
import re
urls = ["https://www.somesite.com/path/path2/path3?param1=value1&param2=value2&param3=value3",
"https://www.anothersite.com/path/path2/path3?param1=value1&param2=value2&param3=value3"]
parseds = [urlparse(url) for url in urls]
newurls = []
for parsed in parseds:
params = parsed[4].split("&")
for i, param in enumerate(params):
newparam = re.sub("=.+", "=PAYLOAD", param)
newurls.append(
parsed[0] +
"://" +
parsed[1] +
parsed[2] +
"?" +
parsed[4].replace(param, newparam)
)

newurls

['https://www.somesite.com/path/path2/path3?param1=PAYLOAD&param2=value2&param3=value3',
'https://www.somesite.com/path/path2/path3?param1=value1&param2=PAYLOAD&param3=value3',
'https://www.somesite.com/path/path2/path3?param1=value1&param2=value2&param3=PAYLOAD',
'https://www.anothersite.com/path/path2/path3?param1=PAYLOAD&param2=value2&param3=value3',
'https://www.anothersite.com/path/path2/path3?param1=value1&param2=PAYLOAD&param3=value3',
'https://www.anothersite.com/path/path2/path3?param1=value1&param2=value2&param3=PAYLOAD']

我已经解决了它:

from urllib.parse import urlparse
url = "https://github.com/search?p=2&q=user&type=Code&name=djalel"
parsed = urlparse(url)
query = parsed.query
params = query.split("&")
new_query = []
for param in params:
l = params.index(param)
param = str(param.split("=")[0]) + "=" + "PAYLOAD"
params[l] = param
new_query.append("&".join(params))
params = query.split("&")
for query in new_query:
print(str(parsed.scheme) + '://' + str(parsed.netloc) + str(parsed.path) + '?' + query)

输出:

https://github.com/search?p=PAYLOAD&q=user&type=Code&name=djalel
https://github.com/search?p=2&q=PAYLOAD&type=Code&name=djalel
https://github.com/search?p=2&q=user&type=PAYLOAD&name=djalel
https://github.com/search?p=2&q=user&type=Code&name=PAYLOAD

最新更新