Python-Url編碼和解碼

來源:互聯網
上載者:User

標籤:bsp   資料   字元   技術   print   decode   轉化   tool   翻譯   

一、為什麼要進行Url編碼

url帶參數的請求格式為(舉例): http://www.baidu.com/s?k1=v1&k2=v2

當請求資料為字典data = {k1:v1, k2:v2},且參數中包含中文或者?、=等特殊符號時,通過url編碼,將data轉化為特定格式k1=v1&k2=v2,並且將中文和特殊符號進行編碼,避免發生歧義

 

二、Url編碼

1、urlencode( )

from urllib import parsefrom urllib import requesturl = ‘http://www.baidu.com/s?‘dict1 ={‘wd‘: ‘百度翻譯‘}url_data = parse.urlencode(dict1) #unlencode()將字典{k1:v1,k2:v2}轉化為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() #讀取url響應結果data = data.decode(‘utf-8‘) #將響應結果用utf8編碼print(data)url_org = parse.unquote(url_data) #解碼urlprint(url_org)              #url_org:wd=百度翻譯str1 = ‘haha哈哈‘str2 = parse.quote(str1)    #將字串進行編碼print(str2)                 #str2=haha%E5%93%88%E5%93%88str3 = parse.unquote(str2)  #解碼字串print(str3)                 #str3=haha哈哈

 

2、quote( ) 和 unquote( )

str1 = ‘haha哈哈‘str2 = parse.quote(str1)   #quote()將字串進行編碼print(str2)                #str2=haha%E5%93%88%E5%93%88str3 = parse.unquote(str2) #解碼字串print(str3)                #str3=haha哈哈

Python-Url編碼和解碼

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.