這篇文章主要介紹了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 cookielib urljoin 現在對應的函數是 urllib.parse.urljoin代碼如下
import urllib.requestimport 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) #輸出cookieprint (response1.read())
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持武林網之家。
新聞熱點
疑難解答