Created
January 13, 2022 10:22
-
-
Save NaClYen/c5ba8a94addcbcad937a246e4b13d3f9 to your computer and use it in GitHub Desktop.
add/update URL query
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
# ref: https://stackoverflow.com/questions/2506379/add-params-to-given-url-in-python | |
import urllib.parse as urlparse | |
from urllib.parse import urlencode | |
url = "http://home.your/echo?id=22" | |
data = {'name': 'nacl', 'age': 18} | |
# 轉換並拆解成陣列 | |
url_parts = list(urlparse.urlparse(url)) | |
# 將第 [4] 的內容轉為 dict | |
query = dict(urlparse.parse_qsl(url_parts[4])) | |
# 更新資料 | |
query.update(data) | |
# encode 並塞回去 | |
url_parts[4] = urlencode(query) | |
# 重新組成網址 | |
final_url = urlparse.urlunparse(url_parts) | |
print(final_url) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment