溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

Python3對urllib和urllib2進行重構的方法

發(fā)布時間:2021-02-02 10:52:26 來源:億速云 閱讀:140 作者:小新 欄目:開發(fā)技術

小編給大家分享一下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 現(xiàn)在對應的函數(shù)是 urllib.parse.urljoin

代碼如下

import urllib.request
import http.cookiejar

url ="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())#打印狀態(tài)碼
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進行重構的方法”有了一定的了解,如果想了解更多相關知識,歡迎關注億速云行業(yè)資訊頻道,感謝各位的閱讀!

向AI問一下細節(jié)

免責聲明:本站發(fā)布的內容(圖片、視頻和文字)以原創(chuàng)、轉載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權內容。

AI