python3urllib2
1. python3.4沒有 urllib2
py3版本之後urllib模塊合並為urllib.request了。
原先的一些函數方法變化不大,只是多加了一個request而已。比如urllib.request.urlopen()
參考:http://www.cnblogs.com/Lands-ljk/p/5447127.html
2. python3.4學習筆記 3.x和2.x的區別,持續更新
python3.4學習筆記(四) 3.x和2.x的區別
在2.x中:print html,3.x中必須改成:print(html)
import urllib2
ImportError: No mole named 'urllib2'
在python3.x裡面,用urllib.request代替urllib2
import thread
ImportError: No mole named 'thread'
在python3.x裡面,用_thread(在前面加一個下劃線)代替thread
在2.x中except Exception,e : 3.x中改為except (Exception):
=================================
print函數
雖然print語法是Python 3中一個很小的改動,且應該已經廣為人知,但依然值得提一下:Python 2中的print語句被Python 3中的print()函數取代,這意味著在Python 3中必須用括弧將需要輸出的對象括起來。
在Python 2中使用額外的括弧也是可以的。但反過來在Python 3中想以Python2的形式不帶括弧調用print函數時,會觸發SyntaxError。
Python 2.7.6
print 'Python', python_version()
print 'Hello, World!'
print('Hello, World!')
print "text", ; print 'print more text on the same line'
輸出:
Hello, World!
Hello, World!
text print more text on the same line
---------------------------
Python 3.4.1
print('Python', python_version())
print('Hello, World!')
print("some text,", end="")
print(' print more text on the same line')
輸出:
Hello, World!
some text, print more text on the same line
print 'Hello, World!'
File "<ipython-input-3-139a7c5835bd>", line 1
print 'Hello, World!'
^
SyntaxError: invalid syntax
注意:在Python中,帶不帶括弧輸出」Hello World」都很正常。
但如果在圓括弧中同時輸出多個對象時,就會創建一個元組,這是因為在Python 2中,print是一個語句,而不是函數調用。
print 'Python', python_version()
print('a', 'b')
print 'a', 'b'
Python 2.7.7
('a', 'b')
a b
---------------------------------
整數除法
由於人們常常會忽視Python 3在整數除法上的改動(寫錯了也不會觸發Syntax Error),所以在移植代碼或在Python 2中執行Python 3的代碼時,需要特別注意這個改動。
所以,我還是會在Python 3的腳本中嘗試用float(3)/2或 3/2.0代替3/2,以此來避免代碼在Python
2環境下可能導致的錯誤(或與之相反,在Python 2腳本中用from __future__ import division來使用Python
3的除法)。
Python 2.7.6
3 / 2 = 1
3 // 2 = 1
3 / 2.0 = 1.5
3 // 2.0 = 1.0
Python 3.4.1
3 / 2 = 1.5
3 // 2 = 1
3 / 2.0 = 1.5
3 // 2.0 = 1.0
---------------------------------
Unicode
Python 2有基於ASCII的str()類型,其可通過單獨的unicode()函數轉成unicode類型,但沒有byte類型。
而在Python 3中,終於有了Unicode(utf-8)字元串,以及兩個位元組類:bytes和bytearrays。
Python 2.7.6
print type(unicode('this is like a python3 str type'))
<type 'unicode'>
print type(b'byte type does not exist')
<type 'str'>
print 'they are really' + b' the same'
they are really the same
print type(bytearray(b'bytearray oddly does exist though'))
<type 'bytearray'>
Python 3.4.1 has <class 'bytes'>
print('and Python', python_version(), end="")
print(' also has', type(bytearray(b'bytearrays')))
and Python 3.4.1 also has <class 'bytearray'>
1
'note that we cannot add a string' + b'bytes for data'
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-13-d3e8942ccf81> in <mole>()
----> 1 'note that we cannot add a string' + b'bytes for data'
TypeError: Can't convert 'bytes' object to str implicitly
=================================
python 2.4 與 python 3.0 的比較
一、 print 從語句變為函數
原: print 1,2+3
改為: print ( 1,2+3 )
二、range 與 xrange
原 : range( 0, 4 ) 結果 是 列表 [0,1,2,3 ]
改為:list( range(0,4) )
原 : xrange( 0, 4 ) 適用於 for 循環的變數控制
改為:range(0,4)
三、字元串
原: 字元串以 8-bit 字元串存儲
改為: 字元串以 16-bit Unicode 字元串存儲
四、try except 語句的變化
在2.x中except Exception,e : 3.x中改為except (Exception):
五、打開文件
原: file( ..... )
或 open(.....)
改為:
只能用 open(.....)
六、從鍵盤錄入一個字元串
原: raw_input( "提示信息" )
改為: input( "提示信息" )
七、bytes 數據類型
A bytes object is an immutable array. The items are 8-bit bytes, represented by integers in the range 0 <= x < 256.
bytes 可以看成是「位元組數組」對象,每個元素是 8-bit 的位元組,取值范圍 0~255。
由於在 python 3.0中字元串以 unicode 編碼存儲,當寫入二進制文件時,字元串無法直接寫入(或讀取),必須以某種方式的編碼為位元組序列後,方可寫入。
(一)字元串編碼(encode) 為 bytes
例: s = "張三abc12"
b = s.encode( 編碼方式)
# b 就是 bytes 類型的數據
# 常用的編碼方式為 : "uft-16" , "utf-8", "gbk", "gb2312", "ascii" , "latin1" 等
# 注 : 當字元串不能編碼為指定的「編碼方式」時,會引發異常
(二) bytes 解碼(decode)為字元串
s = "張三abc12"
b = s.encode( "gbk") # 字元串 s 編碼為 gbk 格式的位元組序列
s1 = b.decode("gbk") # 將位元組序列 b以gbk格式 解碼為字元串
# 說明,當位元組序列不能以指定的編碼格式解碼時會引發異常
(三)使用方法舉例
#coding=gbk
f = open("c:\\1234.txt", "wb")
s = "張三李四abcd1234"
# -------------------------------
# 在 python2.4 中我們可以這樣寫:
# f.write( s )
# 但在 python 3.0中會引發異常
# -------------------------------
b = s.encode("gbk")
f.write( b )
f.close()
input("?")
讀取該文件的例子:
#coding=gbk
f = open("c:\\1234.txt", "rb")
f.seek(0,2) #定位至文件尾
n = f.tell() #讀取文件的位元組數
f.seek(0,0) #重新定位至文件開始處
b = f.read( n )
# ------------------------------
# 在 python 2.4 中 b 是字元串類型
# 要 python 3.0 中 b 是 bytes 類型
# 因此需要按指定的編碼方式確碼
# ------------------------------
s = b.decode("gbk")
print ( s )
# ------------------------------
# 在 python 2.4 中 可以寫作 print s 或 print ( s )
# 要 python 3.0 中 必須寫作 print ( s )
# ------------------------------
f.close()
input("?")
運行後應顯示:
張三李四abcd1234
(四) bytes序列,一但形成,其內容是不可變的,例:
s="ABCD"
b=s.encode("gbk")
print b[0] # 顯示 65
b[0] = 66
# 執行該句,出現異常: 'bytes' object does not support item assignment
八、 chr( K ) 與 ord( c )
python 2.4.2以前
chr( K ) 將編碼K 轉為字元,K的范圍是 0 ~ 255
ord( c ) 取單個字元的編碼, 返回值的范圍: 0 ~ 255
python 3.0
chr( K ) 將編碼K 轉為字元,K的范圍是 0 ~ 65535
ord( c ) 取單個字元的編碼, 返回值的范圍: 0 ~ 65535
九、 除法運算符
python 2.4.2以前
10/3 結果為 3
python 3.0
10 / 3 結果為 3.3333333333333335
10 // 3 結果為 3
十、位元組數組對象 --- 新增
(一) 初始化
a = bytearray( 10 )
# a 是一個由十個位元組組成的數組,其每個元素是一個位元組,類型借用 int
# 此時,每個元素初始值為 0
(二) 位元組數組 是可變的
a = bytearray( 10 )
a[0] = 25
# 可以用賦值語句更改其元素,但所賦的值必須在 0 ~ 255 之間
(三) 位元組數組的切片仍是位元組數組
(四) 字元串轉化為位元組數組
#coding=gbk
s ="你好"
b = s.encode( "gbk") # 先將字元串按某種「GBK」編碼方式轉化為 bytes
c = bytearray( b ) #再將 bytes 轉化為 位元組數組
也可以寫作
c = bytearray( "你好", "gbk")
(五) 位元組數組轉化為字元串
c = bytearray( 4 )
c[0] = 65 ; c[1]=66; c[2]= 67; c[3]= 68
s = c.decode( "gbk" )
print ( s )
# 應顯示: ABCD
(六) 位元組數組可用於寫入文本文件
#coding=gbk
f = open("c:\\1234.txt", "wb")
s = "張三李四abcd1234"
# -------------------------------
# 在 python2.4 中我們可以這樣寫:
# f.write( s )
# 但在 python 3.0中會引發異常
# -------------------------------
b = s.encode("gbk")
f.write( b )
c=bytearray( "王五","gbk")
f.write( c )
f.close()
input("?")
3. python3中怎麼沒有urllib2
urllib2是python2自帶的模塊,不需要下載。
urllib2在python3.x中被改為urllib ,你直接輸入urllib就可以了
>>>importurllib
下圖是我電腦上的Python3.5版本的
4. python3.4沒有urllib2怎麼辦
python 3.x中urllib庫和urilib2庫合並成了urllib庫。
其中urllib2.urlopen()變成了urllib.request.urlopen()
urllib2.Request()變成了urllib.request.Request()
5. python3中使用urllib進行https請求
剛入門python學習網路爬蟲基礎,我使用的python版本是python3.6.4,學習的教程參考 Python爬蟲入門教程
python3.6的版本已經沒有urllib2這個庫了,所以我也不需要糾結urllib和urllib2的區別和應用場景
參考這篇官方文檔 HOWTO Fetch Internet Resources Using The urllib Package 。關於http(s)請求一般就get和post兩種方式較為常用,所以寫了以下兩個小demo,url鏈接隨便找的,具體場景具體變化,可參考注釋中的基本思路
POST請求:
GET請求:
注意,
使用ssl創建未經驗證的上下文,在urlopen中需傳入上下文參數
urllib.request.urlopen(full_url, context=context)
這是Python 升級到 2.7.9 之後引入的一個新特性,所以在使用urlopen打開https鏈接會遇到如下報錯:
ssl.SSLError: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c:777)
所以,當使用urllib.urlopen打開一個 https 鏈接時,需要先驗證一次 SSL 證書
context = ssl._create_unverified_context()
或者或者導入ssl時關閉證書驗證
ssl._create_default_https_context =ssl._create_unverified_context
6. python3中urllib2找不到怎麼辦
在python2中使用的urllib2庫在python3中不存在怎麼解決呢?在python3中是urllib.request.urlopen代替了urllib2.
最後列印結果
7. python urllib2模塊 在哪裡下載
urllib2是python自帶的模塊,不需要下載。
urllib2在python3.x中被改為urllib.request
8. Python3中的requests模塊怎樣用
Requests 是用Python語言編寫,基於 urllib,採用 Apache2 Licensed 開源協議的 HTTP 庫。它比 urllib 更加方便,可以節約我們大量的工作,完全滿足 HTTP 測試需求。Requests 的哲學是以 PEP 20 的習語為中心開發的,所以它比 urllib 更加 Pythoner。更重要的一點是它支持 Python3
開始要導入 Requests 模塊:
1
import requests
然後,嘗試獲取某個網頁。本例子中,我們來獲取 Github 的公共時間線:
1
r = requests.get('https://api.github.com')
可參考網址:www.cnblogs.com/wangyinghao/p/10712328.html
9. python urllib需要安裝嗎
urllib2是python自帶的模塊,不需要下載。 urllib2在python3.x中被改為urllib.request
10. python3中為什麼urlparse.urljoin沒有了
python3對urllib和urllib2進行了重構,拆分成了urllib.request, urllib.response, urllib.parse, urllib.error等幾個子模塊,這樣的架構從邏輯和結構上說更加合理。
urljoin現在對應的函數是urllib.parse.urljoin