參考:
我們知道,url 中是不能出現一些特殊的符號的,有些符號有特殊的用途。比如以 get 方式提交資料的時候,會在 url 中新增 key=value 這樣的字串,所以在 value 中是不允許有 '=',因此要對其進行編碼;與此同時伺服器接收到這些引數的時候,要進行解碼,還原成原始的資料。這個時候,這些輔助方法會很有用:
我們接下來執行一下下面的指令碼來加深理解。
01
import
urllib
02
data
=
'name = ~nowamagic+5'
03
04
data1
=
urllib.quote(data)
05
print
data1
# result: name%20%3d%20%7enowamagic%2b5
06
print
urllib.unquote(data1)
# name = ~nowamagic+5
07
08
data2
=
urllib.quote_plus(data)
09
print
data2
# result: name+%3d+%7enowamagic%2b5
10
print
urllib.unquote_plus(data2)
# name = ~nowamagic+5
11
12
data3
=
urllib.urlencode()
13
print
data3
# result: age=200&name=nowamagic-gonn
14
15
data4
=
urllib.pathname2url(r
'd:/a/b/c/23.php'
)
16
print
data4
# result: ///d://a/b/c/23.php
17
print
urllib.url2pathname(data4)
# result: d:/a/b/c/23.php
在 python shell 裡執行的具體情況為:
01
python
2.7
.
5
(default, may
15
2013
,
22
:
44
:
16
) [msc v.
1500
64
bit (amd64)] on win32
02
type
,
"credits"
or
"license()"
for
more information.
03
>>>
import
urllib
04
>>> data
=
'name = ~nowamagic+5'
05
>>> data1
=
urllib.quote(data)
06
>>>
print
data1
07
name
%
20
%
3d
%
20
%
7enowamagic
%
2b5
08
>>>
print
urllib.unquote(data1)
09
name
=
~nowamagic
+
5
10
>>> data2
=
urllib.quote_plus(data)
11
>>>
print
data2
12
name
+
%
3d
+
%
7enowamagic
%
2b5
13
>>>
print
urllib.unquote_plus(data2)
14
name
=
~nowamagic
+
5
15
>>> data3
=
urllib.urlencode()
16
>>>
print
data3
17
age
=
200
&name
=
nowamagic
-
gonn
18
>>> data4
=
urllib.pathname2url(r
'd:/a/b/c/23.php'
)
19
>>>
print
data4
20
/
/
/
d:
/
/
a
/
b
/
c
/
23.php
21
>>>
print
urllib.url2pathname(data4)
22
d:\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...