fromurllib.parseimporturlparse,urlunparse,urlencode,parse_qsdefadd_query_params(url,params):"""URL에 쿼리 파라미터 추가"""parsed=urlparse(url)# 기존 쿼리 파싱existing=parse_qs(parsed.query)# 새 파라미터 병합existing.update({k:[v]ifnotisinstance(v,list)elsevfork,vinparams.items()})# 쿼리 문자열 재생성new_query=urlencode(existing,doseq=True)# URL 재조립returnurlunparse(parsed._replace(query=new_query))url="https://example.com/search?q=python"new_url=add_query_params(url,{'page':'2','sort':'date'})print(new_url)# https://example.com/search?q=python&page=2&sort=date
8. 안전 문자 지정
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
fromurllib.parseimportquotepath="/path/to/file with spaces"# 기본: / 는 인코딩되지 않음print(quote(path))# /path/to/file%20with%20spaces# safe 지정: 인코딩하지 않을 문자print(quote(path,safe=''))# %2Fpath%2Fto%2Ffile%20with%20spaces# 추가 안전 문자print(quote("a=b&c=d",safe='=&'))# a=b&c=d
https://user:pass@example.com:8080/path/to/page?name=alice#section
\___/ \__/ \__/ \_________/ \__/\__________/ \_________/ \_____/
| | | | | | | |
scheme user pass host port path query fragment
\________/
userinfo
\__________________/
netloc
자주 하는 실수
1. parse_qs 값이 리스트
1
2
3
4
5
6
7
8
9
10
11
12
13
fromurllib.parseimportparse_qsparams=parse_qs("name=alice")# 잘못: params['name']은 문자열이 아님# print(params['name'].upper()) # AttributeError# 올바름: 리스트에서 첫 번째 값print(params['name'][0].upper())# ALICE# 또는 parse_qsl 사용fromurllib.parseimportparse_qslparams_list=dict(parse_qsl("name=alice"))print(params_list['name'].upper())# ALICE
2. 인코딩 중복
1
2
3
4
5
6
7
8
fromurllib.parseimportquote# 이미 인코딩된 문자열을 다시 인코딩encoded="hello%20world"double_encoded=quote(encoded)print(double_encoded)# hello%2520world (잘못!)# quote의 safe에 %를 추가하거나, 먼저 디코딩