Last active
January 29, 2024 12:25
-
-
Save rokcarl/20b5bf8dd9b1998880b7 to your computer and use it in GitHub Desktop.
Update URL parameters in Python 3.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import urllib.parse | |
url = "http://stackoverflow.com/search?q=question" | |
params = {'lang':'en','tag':'python'} | |
url_parts = list(urllib.parse.urlparse(url)) | |
query = dict(urllib.parse.parse_qsl(url_parts[4])) | |
query.update(params) | |
url_parts[4] = urllib.parse.urlencode(query) | |
print(urllib.parse.urlunparse(url_parts)) |
morningdip
commented
May 5, 2022
Thanks man! you the goat! 🚀
Fixed version:
import urllib.parse
url = "http://stackoverflow.com/search?q=question"
params = {'lang':'en','tag':'python'}
url_parts = urllib.parse.urlparse(url)
query = urllib.parse.parse_qs(url_parts.query, keep_blank_values=True)
query.update(params)
new_url = url_parts._replace(query=urllib.parse.urlencode(query, doseq=True)).geturl()
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment