python3对urllib和urllib2进行了重构
生活随笔
收集整理的這篇文章主要介紹了
python3对urllib和urllib2进行了重构
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
python3對urllib和urllib2進行了重構,拆分成了urllib.request,urllib.response, urllib.parse, urllib.error等幾個子模塊,這樣的架構從邏輯和結構上說更加合理。urllib庫無需安裝,python3自帶。python 3.x中將urllib庫和urilib2庫合并成了urllib庫。 其中
urllib2.urlopen() 變成了 urllib.request.urlopen() urllib2.Request() 變成了 urllib.request.Request() python2中的 cookielib 改為 http.cookiejar. import http.cookiejar 代替 import cookieliburljoin 現在對應的函數是 urllib.parse.urljoin
''' 遇到問題沒人解答?小編創建了一個Python學習交流QQ群:579817333 尋找有志同道合的小伙伴,互幫互助,群里還有不錯的視頻學習教程和PDF電子書! ''' import urllib.request import http.cookiejarurl ="http://www.baidu.com"print ('第一種方法') response1=urllib.request.urlopen(url) print (response1.getcode()) print (len(response1.read()))print ('第二種方法') request=urllib.request.Request(url) request.add_header("user-agent","Mozilla/5.0")#將爬蟲偽裝成瀏覽器 response2=urllib.request.urlopen(request) print (response2.getcode())#打印狀態碼 print (len(response2.read()))#打印內容長度print ('第三種方法') cj = http.cookiejar.CookieJar() opener = urllib.request.build_opener(urllib.request.HTTPCookieProcessor(cj)) urllib.request.install_opener(opener) response3=urllib.request.urlopen(url) print (response1.getcode()) print (cj) #輸出cookie print (response1.read())總結
以上是生活随笔為你收集整理的python3对urllib和urllib2进行了重构的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 关于python中多态的理解。
- 下一篇: Python 函数缓存 (Functio