當我們要從 URL 中獲取參數時,
我們可以使用 urlparse 函數來解析 URL,
並使用 parse_qs 函數來解析查詢參數。
假設有以下 URL:http://example.com/?name=John&age=30&gender=male
示範如何使用 urlparse 和 parse_qs:
# -*- coding: utf-8 -*-
"""
Created on Tue Aug 29 20:21:54 2023
@author: SavingKing
"""
from urllib.parse import urlparse, parse_qs
url = "http://example.com/?name=John&age=30&gender=male"
parsed_url = urlparse(url)
query_params = parse_qs(parsed_url.query)
print("Parsed URL:", parsed_url)
print("Query Parameters:", query_params)
print("Name:", query_params['name'][0])
print("Age:", query_params['age'][0])
print("Gender:", query_params['gender'][0])輸出結果:

在這個示範中,我們使用了 urlparse 來解析 URL,
並使用 parse_qs 來解析查詢參數。
注意,parse_qs 返回的是一個字典,
其中鍵是參數名,值是包含參數值的列表。
因此,我們使用 query_params['name'][0] 來獲取名為 name 的參數的值。
可以自己寫出相似的程式:
# -*- coding: utf-8 -*-
"""
Created on Fri Nov 24 23:35:04 2023
@author: SavingKing
"""
url = "http://example.com/?name=John&age=30&gender=male"
strr = url.split("?")[1]
#'name=John&age=30&gender=male'
lis = strr.split("&")
#['name=John', 'age=30', 'gender=male']
dic ={}
for ele in lis:
k,v = ele.split("=")
dic[k]=v
print("dic:\n",dic)執行結果:

推薦hahow線上學習python: https://igrape.net/30afN







![Python如何串接OpenAI /Claude /Gemini API自動將大量維修紀錄JSON轉自然語言描述(並避免中斷資料遺失)response = client.chat.completions.create() ; reply = response.choices[0].message.content Python如何串接OpenAI /Claude /Gemini API自動將大量維修紀錄JSON轉自然語言描述(並避免中斷資料遺失)response = client.chat.completions.create() ; reply = response.choices[0].message.content](https://i1.wp.com/savingking.com.tw/wp-content/uploads/2025/07/20250716084059_0_c5b368.png?quality=90&zoom=2&ssl=1&resize=350%2C233)
![Python Logging 完全指南:從基礎到實戰應用; import logging ; logging.basicConfig(level=logging.INFO, handlers=[ logging.StreamHandler(), logging.FileHandler(‘app.log’, mode=’a’, encoding=’utf-8′)] ) ; inspect.currentframe().f_code.co_name #動態取得funcName Python Logging 完全指南:從基礎到實戰應用; import logging ; logging.basicConfig(level=logging.INFO, handlers=[ logging.StreamHandler(), logging.FileHandler(‘app.log’, mode=’a’, encoding=’utf-8′)] ) ; inspect.currentframe().f_code.co_name #動態取得funcName](https://i1.wp.com/savingking.com.tw/wp-content/uploads/2025/10/20251021155823_0_c16012.png?quality=90&zoom=2&ssl=1&resize=350%2C233)

近期留言