Movatterモバイル変換


[0]ホーム

URL:


Navigation

21.8.urllib.parse — Parse URLs into components

Source code:Lib/urllib/parse.py


This module defines a standard interface to break Uniform Resource Locator (URL)strings up in components (addressing scheme, network location, path etc.), tocombine the components back into a URL string, and to convert a “relative URL”to an absolute URL given a “base URL.”

The module has been designed to match the Internet RFC on Relative UniformResource Locators. It supports the following URL schemes:file,ftp,gopher,hdl,http,https,imap,mailto,mms,news,nntp,prospero,rsync,rtsp,rtspu,sftp,shttp,sip,sips,snews,svn,svn+ssh,telnet,wais.

Theurllib.parse module defines functions that fall into two broadcategories: URL parsing and URL quoting. These are covered in detail inthe following sections.

21.8.1. URL Parsing

The URL parsing functions focus on splitting a URL string into its components,or on combining URL components into a URL string.

urllib.parse.urlparse(urlstring,scheme='',allow_fragments=True)

Parse a URL into six components, returning a 6-tuple. This corresponds to thegeneral structure of a URL:scheme://netloc/path;parameters?query#fragment.Each tuple item is a string, possibly empty. The components are not broken up insmaller parts (for example, the network location is a single string), and %escapes are not expanded. The delimiters as shown above are not part of theresult, except for a leading slash in thepath component, which is retained ifpresent. For example:

>>>fromurllib.parseimporturlparse>>>o=urlparse('http://www.cwi.nl:80/%7Eguido/Python.html')>>>oParseResult(scheme='http', netloc='www.cwi.nl:80', path='/%7Eguido/Python.html',            params='', query='', fragment='')>>>o.scheme'http'>>>o.port80>>>o.geturl()'http://www.cwi.nl:80/%7Eguido/Python.html'

Following the syntax specifications inRFC 1808, urlparse recognizesa netloc only if it is properly introduced by ‘//’. Otherwise theinput is presumed to be a relative URL and thus to start witha path component.

>>>fromurllib.parseimporturlparse>>>urlparse('//www.cwi.nl:80/%7Eguido/Python.html')ParseResult(scheme='', netloc='www.cwi.nl:80', path='/%7Eguido/Python.html',           params='', query='', fragment='')>>>urlparse('www.cwi.nl/%7Eguido/Python.html')ParseResult(scheme='', netloc='', path='www.cwi.nl/%7Eguido/Python.html',           params='', query='', fragment='')>>>urlparse('help/Python.html')ParseResult(scheme='', netloc='', path='help/Python.html', params='',           query='', fragment='')

If thescheme argument is specified, it gives the default addressingscheme, to be used only if the URL does not specify one. The default value forthis argument is the empty string.

If theallow_fragments argument is false, fragment identifiers are notallowed. The default value for this argument isTrue.

The return value is actually an instance of a subclass oftuple. Thisclass has the following additional read-only convenience attributes:

AttributeIndexValueValue if not present
scheme0URL scheme specifierempty string
netloc1Network location partempty string
path2Hierarchical pathempty string
params3Parameters for last pathelementempty string
query4Query componentempty string
fragment5Fragment identifierempty string
username User nameNone
password PasswordNone
hostname Host name (lower case)None
port Port number as integer,if presentNone

See sectionStructured Parse Results for more information on the resultobject.

Changed in version 3.2:Added IPv6 URL parsing capabilities.

Changed in version 3.3:The fragment is now parsed for all URL schemes (unlessallow_fragment isfalse), in accordance withRFC 3986. Previously, a whitelist ofschemes that support fragments existed.

urllib.parse.parse_qs(qs,keep_blank_values=False,strict_parsing=False,encoding='utf-8',errors='replace')

Parse a query string given as a string argument (data of typeapplication/x-www-form-urlencoded). Data are returned as adictionary. The dictionary keys are the unique query variable names and thevalues are lists of values for each name.

The optional argumentkeep_blank_values is a flag indicating whether blankvalues in percent-encoded queries should be treated as blank strings. A true valueindicates that blanks should be retained as blank strings. The default falsevalue indicates that blank values are to be ignored and treated as if they werenot included.

The optional argumentstrict_parsing is a flag indicating what to do withparsing errors. If false (the default), errors are silently ignored. If true,errors raise aValueError exception.

The optionalencoding anderrors parameters specify how to decodepercent-encoded sequences into Unicode characters, as accepted by thebytes.decode() method.

Use theurllib.parse.urlencode() function (with thedoseqparameter set toTrue) to convert such dictionaries into querystrings.

Changed in version 3.2:Addencoding anderrors parameters.

urllib.parse.parse_qsl(qs,keep_blank_values=False,strict_parsing=False,encoding='utf-8',errors='replace')

Parse a query string given as a string argument (data of typeapplication/x-www-form-urlencoded). Data are returned as a list ofname, value pairs.

The optional argumentkeep_blank_values is a flag indicating whether blankvalues in percent-encoded queries should be treated as blank strings. A true valueindicates that blanks should be retained as blank strings. The default falsevalue indicates that blank values are to be ignored and treated as if they werenot included.

The optional argumentstrict_parsing is a flag indicating what to do withparsing errors. If false (the default), errors are silently ignored. If true,errors raise aValueError exception.

The optionalencoding anderrors parameters specify how to decodepercent-encoded sequences into Unicode characters, as accepted by thebytes.decode() method.

Use theurllib.parse.urlencode() function to convert such lists of pairs intoquery strings.

Changed in version 3.2:Addencoding anderrors parameters.

urllib.parse.urlunparse(parts)

Construct a URL from a tuple as returned byurlparse(). Thepartsargument can be any six-item iterable. This may result in a slightlydifferent, but equivalent URL, if the URL that was parsed originally hadunnecessary delimiters (for example, a? with an empty query; the RFCstates that these are equivalent).

urllib.parse.urlsplit(urlstring,scheme='',allow_fragments=True)

This is similar tourlparse(), but does not split the params from the URL.This should generally be used instead ofurlparse() if the more recent URLsyntax allowing parameters to be applied to each segment of thepath portionof the URL (seeRFC 2396) is wanted. A separate function is needed toseparate the path segments and parameters. This function returns a 5-tuple:(addressing scheme, network location, path, query, fragment identifier).

The return value is actually an instance of a subclass oftuple. Thisclass has the following additional read-only convenience attributes:

AttributeIndexValueValue if not present
scheme0URL scheme specifierempty string
netloc1Network location partempty string
path2Hierarchical pathempty string
query3Query componentempty string
fragment4Fragment identifierempty string
username User nameNone
password PasswordNone
hostname Host name (lower case)None
port Port number as integer,if presentNone

See sectionStructured Parse Results for more information on the resultobject.

urllib.parse.urlunsplit(parts)

Combine the elements of a tuple as returned byurlsplit() into acomplete URL as a string. Theparts argument can be any five-itemiterable. This may result in a slightly different, but equivalent URL, if theURL that was parsed originally had unnecessary delimiters (for example, a ?with an empty query; the RFC states that these are equivalent).

urllib.parse.urljoin(base,url,allow_fragments=True)

Construct a full (“absolute”) URL by combining a “base URL” (base) withanother URL (url). Informally, this uses components of the base URL, inparticular the addressing scheme, the network location and (part of) thepath, to provide missing components in the relative URL. For example:

>>>fromurllib.parseimporturljoin>>>urljoin('http://www.cwi.nl/%7Eguido/Python.html','FAQ.html')'http://www.cwi.nl/%7Eguido/FAQ.html'

Theallow_fragments argument has the same meaning and default as forurlparse().

Note

Ifurl is an absolute URL (that is, starting with// orscheme://),theurl‘s host name and/or scheme will be present in the result. For example:

>>>urljoin('http://www.cwi.nl/%7Eguido/Python.html',...'//www.python.org/%7Eguido')'http://www.python.org/%7Eguido'

If you do not want that behavior, preprocess theurl withurlsplit() andurlunsplit(), removing possiblescheme andnetloc parts.

urllib.parse.urldefrag(url)

Ifurl contains a fragment identifier, return a modified version ofurlwith no fragment identifier, and the fragment identifier as a separatestring. If there is no fragment identifier inurl, returnurl unmodifiedand an empty string.

The return value is actually an instance of a subclass oftuple. Thisclass has the following additional read-only convenience attributes:

AttributeIndexValueValue if not present
url0URL with no fragmentempty string
fragment1Fragment identifierempty string

See sectionStructured Parse Results for more information on the resultobject.

Changed in version 3.2:Result is a structured object rather than a simple 2-tuple.

21.8.2. Parsing ASCII Encoded Bytes

The URL parsing functions were originally designed to operate on characterstrings only. In practice, it is useful to be able to manipulate properlyquoted and encoded URLs as sequences of ASCII bytes. Accordingly, theURL parsing functions in this module all operate onbytes andbytearray objects in addition tostr objects.

Ifstr data is passed in, the result will also contain onlystr data. Ifbytes orbytearray data ispassed in, the result will contain onlybytes data.

Attempting to mixstr data withbytes orbytearray in a single function call will result in aTypeError being raised, while attempting to pass in non-ASCIIbyte values will triggerUnicodeDecodeError.

To support easier conversion of result objects betweenstr andbytes, all return values from URL parsing functions provideeither anencode() method (when the result containsstrdata) or adecode() method (when the result containsbytesdata). The signatures of these methods match those of the correspondingstr andbytes methods (except that the default encodingis'ascii' rather than'utf-8'). Each produces a value of acorresponding type that contains eitherbytes data (forencode() methods) orstr data (fordecode() methods).

Applications that need to operate on potentially improperly quoted URLsthat may contain non-ASCII data will need to do their own decoding frombytes to characters before invoking the URL parsing methods.

The behaviour described in this section applies only to the URL parsingfunctions. The URL quoting functions use their own rules when producingor consuming byte sequences as detailed in the documentation of theindividual URL quoting functions.

Changed in version 3.2:URL parsing functions now accept ASCII encoded byte sequences

21.8.3. Structured Parse Results

The result objects from theurlparse(),urlsplit() andurldefrag() functions are subclasses of thetuple type.These subclasses add the attributes listed in the documentation forthose functions, the encoding and decoding support described in theprevious section, as well as an additional method:

urllib.parse.SplitResult.geturl()

Return the re-combined version of the original URL as a string. This maydiffer from the original URL in that the scheme may be normalized to lowercase and empty components may be dropped. Specifically, empty parameters,queries, and fragment identifiers will be removed.

Forurldefrag() results, only empty fragment identifiers will be removed.Forurlsplit() andurlparse() results, all noted changes will bemade to the URL returned by this method.

The result of this method remains unchanged if passed back through the originalparsing function:

>>>fromurllib.parseimporturlsplit>>>url='HTTP://www.Python.org/doc/#'>>>r1=urlsplit(url)>>>r1.geturl()'http://www.Python.org/doc/'>>>r2=urlsplit(r1.geturl())>>>r2.geturl()'http://www.Python.org/doc/'

The following classes provide the implementations of the structured parseresults when operating onstr objects:

classurllib.parse.DefragResult(url,fragment)

Concrete class forurldefrag() results containingstrdata. Theencode() method returns aDefragResultBytesinstance.

New in version 3.2.

classurllib.parse.ParseResult(scheme,netloc,path,params,query,fragment)

Concrete class forurlparse() results containingstrdata. Theencode() method returns aParseResultBytesinstance.

classurllib.parse.SplitResult(scheme,netloc,path,query,fragment)

Concrete class forurlsplit() results containingstrdata. Theencode() method returns aSplitResultBytesinstance.

The following classes provide the implementations of the parse results whenoperating onbytes orbytearray objects:

classurllib.parse.DefragResultBytes(url,fragment)

Concrete class forurldefrag() results containingbytesdata. Thedecode() method returns aDefragResultinstance.

New in version 3.2.

classurllib.parse.ParseResultBytes(scheme,netloc,path,params,query,fragment)

Concrete class forurlparse() results containingbytesdata. Thedecode() method returns aParseResultinstance.

New in version 3.2.

classurllib.parse.SplitResultBytes(scheme,netloc,path,query,fragment)

Concrete class forurlsplit() results containingbytesdata. Thedecode() method returns aSplitResultinstance.

New in version 3.2.

21.8.4. URL Quoting

The URL quoting functions focus on taking program data and making it safefor use as URL components by quoting special characters and appropriatelyencoding non-ASCII text. They also support reversing these operations torecreate the original data from the contents of a URL component if thattask isn’t already covered by the URL parsing functions above.

urllib.parse.quote(string,safe='/',encoding=None,errors=None)

Replace special characters instring using the%xx escape. Letters,digits, and the characters'_.-' are never quoted. By default, thisfunction is intended for quoting the path section of URL. The optionalsafeparameter specifies additional ASCII characters that should not be quoted— its default value is'/'.

string may be either astr or abytes.

The optionalencoding anderrors parameters specify how to deal withnon-ASCII characters, as accepted by thestr.encode() method.encoding defaults to'utf-8'.errors defaults to'strict', meaning unsupported characters raise aUnicodeEncodeError.encoding anderrors must not be supplied ifstring is abytes, or aTypeError is raised.

Note thatquote(string,safe,encoding,errors) is equivalent toquote_from_bytes(string.encode(encoding,errors),safe).

Example:quote('/ElNiño/') yields'/El%20Ni%C3%B1o/'.

urllib.parse.quote_plus(string,safe='',encoding=None,errors=None)

Likequote(), but also replace spaces by plus signs, as required forquoting HTML form values when building up a query string to go into a URL.Plus signs in the original string are escaped unless they are included insafe. It also does not havesafe default to'/'.

Example:quote_plus('/ElNiño/') yields'%2FEl+Ni%C3%B1o%2F'.

urllib.parse.quote_from_bytes(bytes,safe='/')

Likequote(), but accepts abytes object rather than astr, and does not perform string-to-bytes encoding.

Example:quote_from_bytes(b'a&\xef') yields'a%26%EF'.

urllib.parse.unquote(string,encoding='utf-8',errors='replace')

Replace%xx escapes by their single-character equivalent.The optionalencoding anderrors parameters specify how to decodepercent-encoded sequences into Unicode characters, as accepted by thebytes.decode() method.

string must be astr.

encoding defaults to'utf-8'.errors defaults to'replace', meaning invalid sequences are replacedby a placeholder character.

Example:unquote('/El%20Ni%C3%B1o/') yields'/ElNiño/'.

urllib.parse.unquote_plus(string,encoding='utf-8',errors='replace')

Likeunquote(), but also replace plus signs by spaces, as required forunquoting HTML form values.

string must be astr.

Example:unquote_plus('/El+Ni%C3%B1o/') yields'/ElNiño/'.

urllib.parse.unquote_to_bytes(string)

Replace%xx escapes by their single-octet equivalent, and return abytes object.

string may be either astr or abytes.

If it is astr, unescaped non-ASCII characters instringare encoded into UTF-8 bytes.

Example:unquote_to_bytes('a%26%EF') yieldsb'a&\xef'.

urllib.parse.urlencode(query,doseq=False,safe='',encoding=None,errors=None)

Convert a mapping object or a sequence of two-element tuples, which mayeither be astr or abytes, to a “percent-encoded”string. If the resultant string is to be used as adata for POSToperation withurlopen() function, then it should beproperly encoded to bytes, otherwise it would result in aTypeError.

The resulting string is a series ofkey=value pairs separated by'&'characters, where bothkey andvalue are quoted usingquote_plus()above. When a sequence of two-element tuples is used as thequeryargument, the first element of each tuple is a key and the second is avalue. The value element in itself can be a sequence and in that case, ifthe optional parameterdoseq is evaluates toTrue, individualkey=value pairs separated by'&' are generated for each element ofthe value sequence for the key. The order of parameters in the encodedstring will match the order of parameter tuples in the sequence.

Whenquery parameter is astr, thesafe,encoding anderrorparameters are passed down toquote_plus() for encoding.

To reverse this encoding process,parse_qs() andparse_qsl() areprovided in this module to parse query strings into Python data structures.

Refer tourllib examples to find out how urlencodemethod can be used for generating query string for a URL or data for POST.

Changed in version 3.2:Query parameter supports bytes and string objects.

See also

RFC 3986 - Uniform Resource Identifiers
This is the current standard (STD66). Any changes to urllib.parse moduleshould conform to this. Certain deviations could be observed, which aremostly for backward compatibility purposes and for certain de-factoparsing requirements as commonly observed in major browsers.
RFC 2732 - Format for Literal IPv6 Addresses in URL’s.
This specifies the parsing requirements of IPv6 URLs.
RFC 2396 - Uniform Resource Identifiers (URI): Generic Syntax
Document describing the generic syntactic requirements for both Uniform ResourceNames (URNs) and Uniform Resource Locators (URLs).
RFC 2368 - The mailto URL scheme.
Parsing requirements for mailto url schemes.
RFC 1808 - Relative Uniform Resource Locators
This Request For Comments includes the rules for joining an absolute and arelative URL, including a fair number of “Abnormal Examples” which govern thetreatment of border cases.
RFC 1738 - Uniform Resource Locators (URL)
This specifies the formal syntax and semantics of absolute URLs.

Table Of Contents

Previous topic

21.6.urllib.request — Extensible library for opening URLs

Next topic

21.9.urllib.error — Exception classes raised by urllib.request

This Page

Quick search

Enter search terms or a module, class or function name.

Navigation

©Copyright 1990-2017, Python Software Foundation.
The Python Software Foundation is a non-profit corporation.Please donate.
Last updated on Sep 19, 2017.Found a bug?
Created usingSphinx 1.2.

[8]ページ先頭

©2009-2025 Movatter.jp