URL地址编码和解码

0. 参考

【整理】关于http(GET或POST)请求中的url地址的编码(encode)和解码(decode)

python3中的urlopen对于中文url是如何处理的?

中文URL的编码问题

1. rfc1738

2.1. The main parts of URLs

   A full BNF description of the URL syntax is given in Section 5.

   In general, URLs are written as follows:

       <scheme>:<scheme-specific-part>

   A URL contains the name of the scheme being used (<scheme>) followed
by a colon and then a string (the <scheme-specific-part>) whose
interpretation depends on the scheme. Scheme names consist of a sequence of characters. The lower case
letters "a"--"z", digits, and the characters plus ("+"), period
("."), and hyphen ("-") are allowed. For resiliency, programs
interpreting URLs should treat upper case letters as equivalent to
lower case in scheme names (e.g., allow "HTTP" as well as "http"). 注意字母不区分大小写

2. python2

2.1

 >>> import urllib
>>> url = 'http://web page.com'
>>> url_en = urllib.quote(url) #空格编码为“%20”
>>> url_plus = urllib.quote_plus(url) #空格编码为“+”
>>> url_en_twice = urllib.quote(url_en)
>>> url
'http://web page.com'
>>> url_en
'http%3A//web%20page.com'
>>> url_plus
'http%3A%2F%2Fweb+page.com'
>>> url_en_twice
'http%253A//web%2520page.com' #出现%25说明是二次编码
#相应解码
>>> urllib.unquote(url_en)
'http://web page.com'
>>> urllib.unquote_plus(url_plus)
'http://web page.com'

2.2 URL含有中文

 >>> import urllib
>>> url_zh = u'http://movie.douban.com/tag/美国'
>>> url_zh_en = urllib.quote(url_zh.encode('utf-8')) #参数为string
>>> url_zh_en
'http%3A//movie.douban.com/tag/%E7%BE%8E%E5%9B%BD'
>>> print urllib.unquote(url_zh_en).decode('utf-8')
http://movie.douban.com/tag/美国

3. python3

3.1

 >>> import urllib
>>> url = 'http://web page.com'
>>> url_en = urllib.parse.quote(url) #注意是urllib.parse.quote
>>> url_plus = urllib.parse.quote_plus(url)
>>> url_en
'http%3A//web%20page.com'
>>> url_plus
'http%3A%2F%2Fweb+page.com'
>>> urllib.parse.unquote(url_en)
'http://web page.com'
>>> urllib.parse.unquote_plus(url_plus)
'http://web page.com'

3.2 URl含中文

 >>> import urllib
>>> url_zh = 'http://movie.douban.com/tag/美国'
>>> url_zh_en = urllib.parse.quote(url_zh)
>>> url_zh_en
'http%3A//movie.douban.com/tag/%E7%BE%8E%E5%9B%BD'
>>> urllib.parse.unquote(url_zh_en)
'http://movie.douban.com/tag/美国'

4. 其他

 >>> help(urllib.urlencode)
Help on function urlencode in module urllib: urlencode(query, doseq=0)
Encode a sequence of two-element tuples or dictionary into a URL query string. If any values in the query arg are sequences and doseq is true, each
sequence element is converted to a separate parameter. If the query arg is a sequence of two-element tuples, the order of the
parameters in the output will match the order of parameters in the
input. >>>
上一篇:IOS基础之 (三) 类的声明和对象的创建


下一篇:封装HttpUrlConnection开箱即用