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.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())#打印狀態碼
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())

 

 

參考鏈接:https://blog.csdn.net/weixin_43550140/article/details/84563205


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM