Python: 如何解析網址? from urllib.parse import urlparse, parse_qs

加入好友
加入社群
Python: 如何解析網址? from urllib.parse import urlparse, parse_qs - 儲蓄保險王

當我們要從 URL 中獲取參數時,
我們可以使用 urlparse 函數來解析 URL,
並使用 parse_qs 函數來解析查詢參數。
假設有以下 URL:
http://example.com/?name=John&age=30&gender=male
示範如何使用 urlparseparse_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])

輸出結果:

Python: 如何解析網址? from urllib.parse import urlparse, parse_qs - 儲蓄保險王

在這個示範中,我們使用了 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)

執行結果:

Python: 如何解析網址? from urllib.parse import urlparse, parse_qs - 儲蓄保險王

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

加入好友
加入社群
Python: 如何解析網址? from urllib.parse import urlparse, parse_qs - 儲蓄保險王

儲蓄保險王

儲蓄險是板主最喜愛的儲蓄工具,最喜愛的投資理財工具則是ETF,最喜愛的省錢工具則是信用卡

You may also like...

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *