이 모듈은 URL(Uniform Resource Locator) 문자열을 구성 요소(주소 지정 체계, 네트워크 위치, 경로 등)로 분리하고, 구성 요소를 다시 URL 문자열로 결합하고, “상대 URL”을 주어진 “기본 URL”에 따라 절대 URL로 변환하는 표준 인터페이스를 정의합니다.
이 모듈은 상대 URL(Relative Uniform Resource Locators)의 인터넷 RFC와 일치하도록 설계되었습니다. 다음과 같은 URL 스킴을 지원합니다: file, ftp, gopher, hdl, http, https, imap, itms-services, mailto, mms, news, nntp, prospero, rsync, rtsp, rtsps, rtspu, sftp, shttp, sip, sips, snews, svn, svn+ssh, telnet, wais, ws, wss.
CPython 구현 상세: The inclusion of the itms-services URL scheme can prevent an app from
passing Apple’s App Store review process for the macOS and iOS App Stores.
Handling for the itms-services scheme is always removed on iOS; on
macOS, it may be removed if CPython has been built with the
--with-app-store-compliance option.
urllib.parse 모듈은 두 가지 넓은 범주에 속하는 함수들을 정의합니다: URL 구문 분석과 URL 인용(quoting). 이에 대해서는 다음 섹션에서 자세히 설명합니다.
This module’s functions use the deprecated term netloc (or net_loc),
which was introduced in RFC 1808. However, this term has been obsoleted by
RFC 3986, which introduced the term authority as its replacement.
The use of netloc is continued for backward compatibility.
Parse a URL into six components, returning a 6-item named tuple. This
corresponds to the general structure of a URL:
scheme://netloc/path;parameters?query#fragment.
Each tuple item is a string, possibly empty, or None if
missing_as_none is true.
Not defined component are represented an empty string (by default) or
None if missing_as_none is true.
The components are not broken up
into smaller parts (for example, the network location is a single string), and %
escapes are not expanded. The delimiters as shown above are not part of the
result, except for a leading slash in the path component, which is retained if
present. For example:
The scheme argument gives the default addressing scheme, to be
used only if the URL does not specify one. It should be the same type
(text or bytes) as urlstring or None, except that the '' is
always allowed, and is automatically converted to b'' if appropriate.
If the allow_fragments argument is false, fragment identifiers are not
recognized. Instead, they are parsed as part of the path, parameters
or query component, and fragment is set to None or the empty
string (depending on the value of missing_as_none) in the return value.
반환 값은 네임드 튜플입니다. 즉, 다음과 같은 인덱스나 이름있는 어트리뷰트로 해당 항목에 액세스 할 수 있습니다:
URL에 잘못된 포트가 지정된 경우 port 어트리뷰트를 읽으면 ValueError가 발생합니다. 결과 객체에 대한 자세한 내용은 구조화된 구문 분석 결과 섹션을 참조하십시오.
netloc 어트리뷰트에서 대괄호(square brackets)가 일치하지 않으면 ValueError가 발생합니다.
(IDNA 인코딩에서 사용되는) NFKC 정규화에서 /, ?, #, @ 또는 : 중 하나로 분해(decompose)되는 netloc 어트리뷰트의 문자는 ValueError를 발생시킵니다. 구문 분석하기 전에 URL이 분해(decompose)되면, 에러가 발생하지 않습니다.
모든 네임드 튜플의 경우와 마찬가지로, 서브 클래스는 특히 유용한 몇 가지 추가 메서드와 어트리뷰트를 갖습니다. 그러한 메서드 중 하나는 _replace()입니다. _replace() 메서드는 지정된 필드를 새로운 값으로 대체한 새로운 ParseResult 객체를 반환합니다.
버전 3.10에서 변경: 기본값이 & 인 separator 매개 변수를 추가했습니다. 파이썬 3.10 이전의 파이썬 버전에서는 쿼리 매개 변수 구분 기호로 ;와 &를 모두 사용할 수 있었습니다. &를 기본 구분자 기호로 사용하여, 단일 구분자 키만 허용하도록 변경되었습니다.
버전 3.14부터 폐지됨: Accepting objects with false values (like 0 and []) except empty
strings and byte-like objects and None is now deprecated.
버전 3.10에서 변경: 기본값이 & 인 separator 매개 변수를 추가했습니다. 파이썬 3.10 이전의 파이썬 버전에서는 쿼리 매개 변수 구분 기호로 ;와 &를 모두 사용할 수 있었습니다. &를 기본 구분자 기호로 사용하여, 단일 구분자 키만 허용하도록 변경되었습니다.
Construct a URL from a tuple as returned by urlparse(). The parts
argument can be any six-item iterable.
This may result in a slightly different, but equivalent URL, if the
URL that was parsed originally had unnecessary delimiters (for example,
a ? with an empty query; the RFC states that these are equivalent).
If keep_empty is true, empty strings are kept in the result (for example,
a ? for an empty query), only None components are omitted.
This allows rebuilding a URL that was parsed with option
missing_as_none=True.
By default, keep_empty is true if parts is the result of the
urlparse() call with missing_as_none=True.
버전 3.15.0a5 (unreleased)에서 변경: Added the keep_empty parameter.
이것은 urlparse()와 유사하지만, URL에서 파라미터를 분할하지 않습니다. URL의 path 부분의 각 세그먼트에 파라미터를 적용할 수 있는 최신 URL 문법(RFC 2396을 참조하십시오)이 필요하면 일반적으로 urlparse() 대신 사용해야 합니다. 경로 세그먼트와 파라미터를 분리하려면 별도의 함수가 필요합니다. 이 함수는 5개 항목 네임드 튜플을 반환합니다:
URL에 잘못된 포트가 지정된 경우 port 어트리뷰트를 읽으면 ValueError가 발생합니다. 결과 객체에 대한 자세한 내용은 구조화된 구문 분석 결과 섹션을 참조하십시오.
netloc 어트리뷰트에서 대괄호(square brackets)가 일치하지 않으면 ValueError가 발생합니다.
(IDNA 인코딩에서 사용되는) NFKC 정규화에서 /, ?, #, @ 또는 : 중 하나로 분해(decompose)되는 netloc 어트리뷰트의 문자는 ValueError를 발생시킵니다. 구문 분석하기 전에 URL이 분해(decompose)되면, 에러가 발생하지 않습니다.
Following some of the WHATWG spec that updates RFC 3986, leading C0
control and space characters are stripped from the URL. \n,
\r and tab \t characters are removed from the URL at any position.
Combine the elements of a tuple as returned by urlsplit() into a
complete URL as a string. The parts argument can be any five-item
iterable.
This may result in a slightly different, but equivalent URL, if the
URL that was parsed originally had unnecessary delimiters (for example,
a ? with an empty query; the RFC states that these are equivalent).
If keep_empty is true, empty strings are kept in the result (for example,
a ? for an empty query), only None components are omitted.
This allows rebuilding a URL that was parsed with option
missing_as_none=True.
By default, keep_empty is true if parts is the result of the
urlsplit() call with missing_as_none=True.
버전 3.15.0a5 (unreleased)에서 변경: Added the keep_empty parameter.
“기본 URL”(base)을 다른 URL(url)과 결합하여 전체 (“절대”) URL을 구성합니다. 비형식적으로, 이것은 기본 URL의 구성 요소, 특히 주소 지정 체계, 네트워크 위치 및 경로(의 일부)를 사용하여 상대 URL에 누락된 구성 요소를 제공합니다. 예를 들면:
Because an absolute URL may be passed as the url parameter, it is
generally not secure to use urljoin with an attacker-controlled
url. For example in,
urljoin("https://website.com/users/",username), if username can
contain an absolute URL, the result of urljoin will be the absolute
URL.
버전 3.5에서 변경: RFC 3986에 정의된 의미론과 일치하도록 동작이 갱신되었습니다.
If url contains a fragment identifier, return a modified version of url
with no fragment identifier, and the fragment identifier as a separate
string. If there is no fragment identifier in url, return url unmodified
and an empty string (by default) or None if missing_as_none is true.
반환 값은 네임드 튜플입니다, 항목은 인덱스나 이름 붙은 어트리뷰트로 액세스 할 수 있습니다:
래핑 된 URL(즉, <URL:scheme://host/path>, <scheme://host/path>, URL:scheme://host/path 또는 scheme://host/path 형식의 문자열)에서 URL을 추출합니다. url이 래핑 된 URL이 아니면, 변경 없이 반환됩니다.
The urlsplit() and urlparse() APIs do not perform validation of
inputs. They may not raise errors on inputs that other applications consider
invalid. They may also succeed on some inputs that might not be considered
URLs elsewhere. Their purpose is for practical functionality rather than
purity.
Instead of raising an exception on unusual input, they may instead return some
component parts as empty strings or None (depending on the value of the
missing_as_none argument).
Or components may contain more than perhaps they should.
We recommend that users of these APIs where the values may be used anywhere
with security implications code defensively. Do some verification within your
code before trusting a returned component part. Does that scheme make
sense? Is that a sensible path? Is there anything strange about that
hostname? etc.
What constitutes a URL is not universally well defined. Different applications
have different needs and desired constraints. For instance the living WHATWG
spec describes what user facing web clients such as a web browser require.
While RFC 3986 is more general. These functions incorporate some aspects of
both, but cannot be claimed compliant with either. The APIs and existing user
code with expectations on specific behaviors predate both standards leading us
to be very cautious about making API behavior changes.
URL 구문 분석 함수는 원래 문자열에서만 작동하도록 설계되었습니다. 실제로는, 적절히 인용되고 인코딩된 URL을 ASCII 바이트 시퀀스로 조작할 수 있으면 유용합니다. 따라서, 이 모듈의 URL 구문 분석 함수는 모두 str 객체 외에 bytes와 bytearray 객체에서 작동합니다.
str과 bytes 간에 결과 객체를 쉽게 변환 할 수 있도록, URL 구문 분석 함수의 모든 반환 값은 encode() 메서드(결과에 str 데이터가 포함될 때)나 decode() 메서드(결과에 bytes 데이터가 포함될 때)를 제공합니다. 이러한 메서드의 서명은 해당 str와 bytes 메서드의 서명과 일치합니다 (기본 인코딩이 'utf-8'가 아니라 'ascii'라는 점은 예외입니다). 각각은 bytes 데이터(encode() 메서드의 경우)나 str 데이터(decode() 메서드의 경우)를 포함하는 해당 형의 값을 생성합니다.
ASCII가 아닌 데이터를 포함할 수 있는 잘못 인용된 URL에서 작동할 가능성이 있는 응용 프로그램은 URL 구문 분석 메서드를 호출하기 전에 바이트열에서 문자로 자체 디코딩을 수행할 필요가 있습니다.
이 섹션에서 설명하는 동작은 URL 구문 분석 함수에만 적용됩니다. URL 인용 함수는 개별 URL 인용 함수의 설명서에 기술된 대로 바이트 시퀀스를 생성하거나 소비할 때 자체 규칙을 사용합니다.
버전 3.2에서 변경: URL 구문 분석 함수는 이제 ASCII 인코딩된 바이트 시퀀스를 받아들입니다.
Return the re-combined version of the original URL as a string. This may
differ from the original URL in that the scheme may be normalized to lower
case and empty components may be dropped. Specifically, empty parameters,
queries, and fragment identifiers will be removed unless the URL was parsed
with missing_as_none=True.
URL 인용(quoting) 함수는 특수 문자를 인용하고 비 ASCII 텍스트를 적절히 인코딩하여 프로그램 데이터를 취해서 URL 구성 요소로 안전하게 사용할 수 있도록 하는 데 중점을 둡니다. 또한 해당 작업이 위의 URL 구문 분석 함수로 처리되지 않는 경우 URL 구성 요소의 내용에서 원래 데이터를 다시 만들기 위해 이러한 작업을 뒤집는 것도 지원합니다.
%xx 이스케이프를 사용하여 string의 특수 문자를 치환합니다. 글자, 숫자 및 문자 '_.-~'는 절대 인용되지 않습니다. 기본적으로, 이 함수는 URL의 경로 섹션을 인용하기 위한 것입니다. 선택적 safe 매개 변수는 인용해서는 안 되는 추가 ASCII 문자를 지정합니다 — 기본값은 '/'입니다.
버전 3.7에서 변경: URL 문자열 인용을 RFC 2396에서 RFC 3986으로 옮겼습니다. “~”는 이제 예약되지 않은 문자 집합에 포함됩니다.
선택적 encoding과 errors 매개 변수는 str.encode() 메서드에서 받아들이는 것처럼 비 ASCII 문자를 처리하는 방법을 지정합니다. encoding의 기본값은 'utf-8'입니다. errors의 기본값은 'strict'로, 지원되지 않는 문자는 UnicodeEncodeError를 발생시킴을 의미합니다. string이 bytes이면 encoding과 errors를 제공해서는 안 됩니다, 그렇지 않으면 TypeError가 발생합니다.
quote()와 유사하지만, URL로 이동하기 위한 쿼리 문자열을 만들 때 HTML 폼값을 인용하는 데 필요한 대로 스페이스를 더하기 부호로 치환하기도 합니다. safe에 포함되지 않으면 원래 문자열의 더하기 부호가 이스케이프 됩니다. 또한 safe의 기본값은 '/'가 아닙니다.
str이나 bytes 객체를 포함할 수 있는 매핑 객체나 두 요소 튜플의 시퀀스를 퍼센트 인코딩된 ASCII 텍스트 문자열로 변환합니다. 결과 문자열을 urlopen() 함수를 사용하여 POST 연산을 위한 data로 사용하려면, 바이트열로 인코딩해야 합니다, 그렇지 않으면 TypeError가 발생합니다.
결과 문자열은 '&' 문자로 구분된 일련의 key=value 쌍이고, 여기서 key와 value는 quote_via 함수를 사용하여 인용됩니다. 기본적으로, quote_plus()가 값을 인용하는 데 사용되는데, 스페이스는 '+' 문자로 인용되고 ‘/’ 문자는 %2F로 인코딩되어 GET 요청 표준(application/x-www-form-urlencoded)을 따름을 뜻합니다. quote_via로 전달될 수 있는 대체 함수는 quote()이며, 스페이스를 %20로 인코딩하고 ‘/’ 문자를 인코딩하지 않습니다. 무엇을 인용할지를 최대한 제어하려면, quote를 사용하고 safe의 값을 지정하십시오.
query 인자에 두 요소 튜플의 시퀀스가 사용될 때, 각 튜플의 첫 번째 요소는 키이고 두 번째 요소는 값입니다. 값 요소 자체는 시퀀스일 수 있으며, 이 경우 선택적 매개 변수 doseq가 True로 평가되면, '&'로 구분된 개별 key=value 쌍이 키에 대한 값 시퀀스의 각 요소에 대해 생성됩니다. 인코딩된 문자열의 파라미터 순서는 시퀀스의 파라미터 튜플 순서와 일치합니다.
safe, encoding 및 errors 매개 변수는 quote_via로 전달됩니다 (encoding과 errors 매개 변수는 쿼리 요소가 str일 때만 전달됩니다).
이 인코딩 프로세스를 뒤집기 위해, 쿼리 문자열을 파이썬 데이터 구조로 구문 분석하기 위해 이 모듈에서 parse_qs()와 parse_qsl()이 제공됩니다.