Skip to content

Instantly share code, notes, and snippets.

@NaClYen
Created January 13, 2022 10:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save NaClYen/c5ba8a94addcbcad937a246e4b13d3f9 to your computer and use it in GitHub Desktop.
Save NaClYen/c5ba8a94addcbcad937a246e4b13d3f9 to your computer and use it in GitHub Desktop.
add/update URL query
# 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