【URL Quoting】
The URL quoting functions focus on taking program data and making it safe for use as URL components by quoting special characters and appropriately encoding non-ASCII text. They also support reversing these operations to recreate the original data from the contents of a URL component.
URL quoting函数作用是将数据能够作为url的一部分,包括处理特殊字符,及编码非ASCII文本。quoting函数也支持逆转以还原数据。
urllib.parse.
quote
(string, safe=’/’, encoding=None, errors=None)
Replace special characters in string using the %xx
escape. Letters, digits, and the characters '_.-'
are never quoted.
Note that quote(string, safe, encoding, errors)
is equivalent to quote_from_bytes(string.encode(encoding, errors), safe)
.
Example: quote('/El Ni駉/')
yields '/El%20Ni%C3%B1o/'
.
urllib.parse.
quote_plus
(string, safe=”, encoding=None, errors=None)- Like
quote()
, but also replace spaces by plus signs, as required for quoting 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 in safe. It also does not have safe default to'/'
. - Example:
quote_plus('/El Ni駉/')
yields'%2FEl+Ni%C3%B1o%2F'
. - 在quote的基础上,把空格变为’+’,连’/’也会被转义。
urllib.parse.
unquote
(string, encoding=’utf-8′, errors=’replace’)- string must be a
unquote()
, but also replace plus signs by spaces, as required for unquoting HTML form values. - string must be a
quote_plus()
is used to quote the values, which means spaces are quoted as a'+'
character and ‘/’ characters are encoded as%2F
, which follows the standard for GET requests (application/x-www-form-urlencoded
). An alternate function that can be passed as quote_via isquote()
, which will encode spaces as%20
and not encode ‘/’ characters. For maximum control of what is quoted, usequote
and specify a value for safe.The safe, encoding, and errors parameters are passed down to quote_via (the encoding and errors parameters are only passed when a query element is a
parse_qs()
andparse_qsl()
are provided in this module to parse query strings into Python data structures.【Example】
1、Here is an example session that uses the
GET
method to retrieve a URL containing parameters:2、The following example uses the
POST
method instead. Note that params output from urlencode is encoded to bytes before it is sent to urlopen as data:POST encode后的数据要转换为bytes!!!
3、The following example uses an explicitly specified HTTP proxy, overriding environment settings:
4、The following example uses an explicitly specified HTTP proxy, overriding environment settings: