Last active
September 26, 2022 06:18
-
-
Save yangyang5214/2ab4f1425e4180dd94d8a4b18e379040 to your computer and use it in GitHub Desktop.
[append url params] #python
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
# -*- coding: UTF-8 -*- | |
try: | |
import urlparse | |
from urllib import urlencode | |
except: # For Python 3 | |
import urllib.parse as urlparse | |
from urllib.parse import urlencode | |
def append_url_params(url: str, params: dict): | |
""" | |
append dict param for url | |
:param url: https://www.baidu.com | |
:param params: {'a': '1'} | |
:return: https://www.baidu.com?a=1 | |
""" | |
url_parts = list(urlparse.urlparse(url)) | |
query = dict(urlparse.parse_qsl(url_parts[4])) | |
query.update(params) | |
url_parts[4] = urlencode(query) | |
return urlparse.urlunparse(url_parts) | |
if __name__ == '__main__': | |
print(append_url_params('https://www.baidu.com', {'a': '1'})) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment