Python urllib模組的URL編碼解碼功能

2021-07-10 16:00:34 字數 4349 閱讀 5126

參考:

我們知道,url 中是不能出現一些特殊的符號的,有些符號有特殊的用途。比如以 get 方式提交資料的時候,會在 url 中新增 key=value 這樣的字串,所以在 value 中是不允許有 '=',因此要對其進行編碼;與此同時伺服器接收到這些引數的時候,要進行解碼,還原成原始的資料。這個時候,這些輔助方法會很有用:

我們接下來執行一下下面的指令碼來加深理解。

01importurllib

02data='name = ~nowamagic+5'

03

04data1=urllib.quote(data)

05printdata1# result: name%20%3d%20%7enowamagic%2b5

06printurllib.unquote(data1)# name = ~nowamagic+5

07

08data2=urllib.quote_plus(data)

09printdata2# result: name+%3d+%7enowamagic%2b5

10printurllib.unquote_plus(data2)# name = ~nowamagic+5

11

12data3=urllib.urlencode()

13printdata3# result: age=200&name=nowamagic-gonn

14

15data4=urllib.pathname2url(r'd:/a/b/c/23.php')

16printdata4# result: ///d://a/b/c/23.php

17printurllib.url2pathname(data4)# result: d:/a/b/c/23.php

在 python shell 裡執行的具體情況為:

01python2.7.5(default, may152013,22:44:16) [msc v.150064bit (amd64)] on win32

02type,"credits"or"license()"formore information.

03>>>importurllib

04>>> data='name = ~nowamagic+5'

05>>> data1=urllib.quote(data)

06>>>printdata1

07name%20%3d%20%7enowamagic%2b5

08>>>printurllib.unquote(data1)

09name=~nowamagic+5

10>>> data2=urllib.quote_plus(data)

11>>>printdata2

12name+%3d+%7enowamagic%2b5

13>>>printurllib.unquote_plus(data2)

14name=~nowamagic+5

15>>> data3=urllib.urlencode()

16>>>printdata3

17age=200&name=nowamagic-gonn

18>>> data4=urllib.pathname2url(r'd:/a/b/c/23.php')

19>>>printdata4

20///d://a/b/c/23.php

21>>>printurllib.url2pathname(data4)

22d:\a\b\c\23.php

python urllib模組學習筆記

這個模組是最基本最常用的,以前看過,總結一下 coding utf 8 import urllib url 伺服器 proxies 使用 伺服器開啟 r urllib.urlopen url,proxies proxies print r.info print r.getcode print r.g...

Python urllib簡單使用

python的urllib和urllib2模組都做與請求url相關的操作。它們最顯著的差異為 urllib2可以接受乙個request物件,並以此可以來設定乙個url的headers,但是urllib只接收乙個url。urllib模組可以提供進行urlencode的方法,該方法用於get查詢字串的生...

python urllib簡單用法

簡單獲取網頁原始碼 html urlopen 開啟鏈結 print html.read decode utf 8 返回utf 8編碼的 原始碼 模擬傳送post請求 req request postdata parse.urlencode name str1 tel str2 mac str3 re...