Suppose I had a URL composed of a host,(e.g. stackoverflow.com) a path in that host (e.g. questions/ask
) and finally some url arguments (param1=5,param2=st...
)
So the final url would have been something like
http://HOST/PATH?param1=x¶m2=y¶m3=zw
Is there a build in function which would construct that url based on the host, path and params dictionary? I wasn't able to find any way to do that which doesn't involve manual string concatenation, and I feel like this probably shouldn't be done manually if that can be avoided. (Perhaps I'm wrong, since unlike file paths, urls are platform independent and pretty consistent)
I tried using urllib.parse and several other methods, but didn't find one that supported such a general url without some manual concatenation.
I think you're looking for urlunsplit()
. You need to build a list/tuple matching the result from urlsplit()
(5 elements), then urlunsplit()
will do what you want.
from urllib.parse import urlunsplit
urlData = ['https', 'stackoverflow.com', 'questions/ask', 'param1=5¶m2=st', '']
url = urlunsplit(urlData)
print(url)
# https://stackoverflow.com/questions/ask?param1=5¶m2=st