First, why the URL encoding
The request format for URL with parameters is (for example): Http://www.baidu.com/s?k1=v1&k2=v2
When the request data is a dictionary, the database = {k1:v1, k2:v2}, and the parameter contains Chinese or? , = and other special symbols, by URL encoding, the data into a specific format k1=v1&k2=v2, and the Chinese and special symbols are encoded to avoid ambiguity
Second, URL encoding
1, UrlEncode ()
From urllib import parsefrom urllib Import requesturl = ' http://www.baidu.com/s? ' Dict1 ={' wd ': ' Baidu translator '}url_data = Parse.urlencode (Dict1) #unlencode () Convert dictionary {k1:v1,k2:v2} to K1=v1&k2=v2print (Url_data ) #url_data: Wd=%e7%99%be%e5%ba%a6%e7%bf%bb%e8%af%91data = Request.urlopen ((url+url_data)). Read () # Read URL response result data = Data.decode (' utf-8 ') #将响应结果用utf8编码print (data) url_org = Parse.unquote (url_data) #解码urlprint (url_org) #url_org: wd= baidu translation str1 = ' haha haha ' str2 = parse.quote (str1) #将字符串进行编码print (str2) #str2 =haha%e5%93%88%e5% 93%88STR3 = Parse.unquote (str2) #解码字符串print (STR3) #str3 =haha haha
2, quote () and unquote ()
str1 = ' haha haha ' str2 = parse.quote (str1) #quote () encode the string print (str2) #str2 =HAHA%E5%93%88%E5%93%88STR3 = Parse.unquote (STR2) #解码字符串print (STR3) #str3 =haha haha
Python-url encoding and decoding