파이썬(python) URL 쿼리스트링 분리하기
3월 10, 2023
In Python |
Python에서 URL의 쿼리스트링을 분리하기 위해서는 urllib.parse 모듈을 사용함
URL에서 특정 쿼리스트링을 뽑아내는 법
from urllib.parse import urlparse, parse_qs
url = "https://example.com/path?name=John&age=30"
# urlparse 함수를 사용하여 URL의 구성 요소를 추출
parsed_url = urlparse(url)
# parse_qs 함수를 사용하여 쿼리스트링을 분리
query_params = parse_qs(parsed_url.query)
print(query_params)
결과
{'name': ['John'], 'age': ['30']}
URL에서 특정 쿼리스트링을 삭제하는 방법
URL의 쿼리스트링 중에서 특정 파라미터를 삭제하려면 파싱한 후에 딕셔너리 형태로 저장된 쿼리스트링을 삭제하고 다시 URL로 조립해야 함
from urllib.parse import urlparse, urlencode
url = "https://example.com/path?name=John&age=30"
# urlparse 함수를 사용하여 URL의 구성 요소를 추출
parsed_url = urlparse(url)
# 딕셔너리 형태로 저장된 쿼리스트링을 가져옵니다.
query_params = dict(parse_qsl(parsed_url.query))
# 삭제할 파라미터 이름을 지정
param_to_delete = 'age'
# 딕셔너리에서 삭제할 파라미터를 제거
query_params.pop(param_to_delete, None)
# 수정된 쿼리스트링을 URL로 조립
updated_url = parsed_url._replace(query=urlencode(query_params)).geturl()
print(updated_url)
결과
https://example.com/path?name=John