Python爬蟲之urllib庫詳解
一、說明:
urllib庫是python內(nèi)置的一個(gè)http請(qǐng)求庫,requests庫就是基于該庫開發(fā)出來的,雖然requests庫使用更方便,但作為最最基本的請(qǐng)求庫,了解一下原理和用法還是很有必要的。
二、urllib四個(gè)模塊組成:
urllib.request
請(qǐng)求模塊(就像在瀏覽器輸入網(wǎng)址,敲回車一樣)
urllib.error
異常處理模塊(出現(xiàn)請(qǐng)求錯(cuò)誤,可以捕捉這些異常)
urllib.parse
url解析模塊
urllib.robotparser
robots.txt解析模塊,判斷哪個(gè)網(wǎng)站可以爬,哪個(gè)不可以爬,用的比較少
在python2與python3中有所不同
在python2中:
import urllib2 response = urllib2.urlopen('http://www.baidu.com')
在python3中:
import urllib.request response = urllib.request.urlopen('http://www.baidu.com')
三、urllib.request
1、urlopen函數(shù)
urllib.request.urlopen(url, data=None, timeout=socket._GLOBAL_DEFAULT_TIMEOUT,*, cafile=None, capath=None, cadefault=False, context=None)
url參數(shù)
from urllib import request response = request.urlopen('http://www.baidu.com') print(response.read().decode('utf-8'))
data參數(shù)
沒有data參數(shù)時(shí),發(fā)送的是一個(gè)get請(qǐng)求,加上data參數(shù)后,請(qǐng)求就變成了post方式(利用’http://httpbin.org測試網(wǎng)址)
import urllib.request import urllib.parse data1= bytes(urllib.parse.urlencode({'word':'hello'}),encoding='utf-8') response = urllib.request.urlopen('http://httpbin.org/post',data = data1) print(response.read())
data參數(shù)需要bytes類型,所以需要使用bytes()函數(shù)進(jìn)行編碼,而bytes函數(shù)的第一個(gè)參數(shù)需要時(shí)str類型,所以使用urllib.parse.urlencode將字典轉(zhuǎn)化為字符串。
timeout參數(shù)
設(shè)置一個(gè)超時(shí)的時(shí)間,如果在這個(gè)時(shí)間內(nèi)沒有響應(yīng),便會(huì)拋出異常
import urllib.request try: response = urllib.request.urlopen('http://www.baidu.com', timeout=0.001) print(response.read()) except: print('error')
將超時(shí)時(shí)間設(shè)置為0.001秒,在這個(gè)時(shí)間內(nèi),沒有響應(yīng),輸出error
2、response 響應(yīng)類型
import urllib from urllib import request response = urllib.request.urlopen('http://www.baidu.com') print(type(response))
狀態(tài)碼與響應(yīng)頭
import urllib from urllib import request response = urllib.request.urlopen('http://www.baidu.com') print(response.status) print(response.getheaders()) print(response.getheader('Server'))
read方法
import urllib.request response = urllib.request.urlopen('http://www.baidu.com') print(type(response.read())) print(response.read().decode('utf-8'))
response.read()返回的是bytes形式的數(shù)據(jù),所以需要用decode(‘utf-8’)進(jìn)行解碼。
3、Request對(duì)象
如果我們需要發(fā)送復(fù)雜的請(qǐng)求,在urllib庫中就需要使用一個(gè)Request對(duì)象
import urllib.request #直接聲明一個(gè)Request對(duì)象,并把url當(dāng)作參數(shù)直接傳遞進(jìn)來 request = urllib.request.Request('http://www.baidu.com') response = urllib.request.urlopen(request) print(response.read().decode('utf-8'))
聲明了一個(gè)Request對(duì)象,把url當(dāng)作參數(shù)傳遞給這個(gè)對(duì)象,然后把這個(gè)對(duì)昂作為urlopen函數(shù)的參數(shù)
更復(fù)雜的請(qǐng)求,加headers
#利用Request對(duì)象實(shí)現(xiàn)一個(gè)post請(qǐng)求
import urllib.request url = 'http://httpbin.org/post' headers = { 'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.198 Safari/537.36' } data = {'word':'hello'} data = bytes(str(data),encoding='utf-8') req = urllib.request.Request(url = url,data = data,headers = headers,method = 'POST') response = urllib.request.urlopen(req) print(response.read().decode('utf-8'))
上面的這個(gè)請(qǐng)求包含了請(qǐng)求方式、url,請(qǐng)求頭,請(qǐng)求體,邏輯清晰。
Request對(duì)象還有一個(gè)add_header方法,這樣也可以添加多個(gè)鍵值對(duì)的header
4、高級(jí)請(qǐng)求方式
設(shè)置代理
很多網(wǎng)站會(huì)檢測某一段時(shí)間某個(gè)IP的訪問次數(shù)(通過流量統(tǒng)計(jì),系統(tǒng)日志等),如果訪問次數(shù)多的不像正常人,它會(huì)禁止這個(gè)IP的訪問。ProxyHandler(設(shè)置代理的handler),可以變換自己的IP地址。
from urllib import request # 導(dǎo)入request模塊 url = 'http://httpbin.org' # url地址 handler = request.ProxyHandler({'http': '122.193.244.243:9999'}) # 使用request模塊ProxyHandler類創(chuàng)建代理 #handler = request.ProxyHandler({"http":"賬號(hào):密碼@'122.193.244.243:9999'"}) #付費(fèi)代理模式 opener = request.build_opener(handler) # 用handler創(chuàng)建opener resp = opener.open(url) # 使用opener.open()發(fā)送請(qǐng)求 print(resp.read()) # 打印返回結(jié)果
cookie
import urllib.request import urllib.parse url = 'https://weibo.cn/5273088553/info' # 正常的方式進(jìn)行訪問 # headers = { # 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.84 Safari/537.36' # } #攜帶cookie進(jìn)行訪問 headers = { 'GET https': '//weibo.cn/5273088553/info HTTP/1.1', 'Host': ' weibo.cn', 'Connection': ' keep-alive', 'Upgrade-Insecure-Requests': ' 1', 'User-Agent': ' Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.84 Safari/537.36', 'Accept': ' text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8', # 'Referer: https':'//weibo.cn/', 'Accept-Language': ' zh-CN,zh;q=0.9', 'Cookie': ' _T_WM=c1913301844388de10cba9d0bb7bbf1e; SUB=_2A253Wy_dDeRhGeNM7FER-CbJzj-IHXVUp7GVrDV6PUJbkdANLXPdkW1NSesPJZ6v1GA5MyW2HEUb9ytQW3NYy19U; SUHB=0bt8SpepeGz439; SCF=Aua-HpSw5-z78-02NmUv8CTwXZCMN4XJ91qYSHkDXH4W9W0fCBpEI6Hy5E6vObeDqTXtfqobcD2D32r0O_5jSRk.; SSOLoginState=1516199821', } request = urllib.request.Request(url=url, headers=headers) response = urllib.request.urlopen(request) # 輸出所有 # print(response.read().decode('gbk')) # 將內(nèi)容寫入文件中 with open('weibo.html', 'wb') as fp: fp.write(response.read())
四、urllib.error
可以捕獲三種異常:URLError,HTTPError(是URLError類的一個(gè)子類),ContentTooShortError
URLError只有一個(gè)reason屬性
HTTPError有三個(gè)屬性:code,reason,headers
import urllib.request from urllib import error try: response = urllib.request.urlopen('http://123.com') except error.URLError as e: print(e.reason)
import urllib from urllib import request from urllib import error #先捕捉http異常,再捕捉url異常 try: response = urllib.request.urlopen('http://123.com') except error.HTTPError as e: print(e.reason, e.code, e.headers) except error.URLError as e: print(e.reason) else: print('RequestSucess!')
五、URL解析urllib.parse
urlparse函數(shù)
該函數(shù)是對(duì)傳入的url進(jìn)行分割,分割成幾部分,并對(duì)每部分進(jìn)行賦值
import urllib from urllib import parse result = urllib.parse.urlparse('http://www,baidu.com/index.html;user?id=5#comment') print(type(result)) print(result)
結(jié)果方便的拆分了url
<class 'urllib.parse.ParseResult'> ParseResult(scheme='http', netloc='www,baidu.com', path='/index.html', params='user', query='id=5', fragment='comment') Process finished with exit code 0
從輸出結(jié)果可以看出,這幾部分包括:協(xié)議類型、域名、路徑、參數(shù)、query、fragment
urlparse有幾個(gè)參數(shù):url,scheme,allow_fragments
在使用urlparse時(shí),可以通過參數(shù)scheme = 'http’的方式來指定默認(rèn)的協(xié)議類型,如果url有協(xié)議類型,scheme參數(shù)就不會(huì)生效了
urlunparse函數(shù)
與urlparse函數(shù)作用相反,是對(duì)url進(jìn)行拼接的
urljoin函數(shù)
用來拼接url
urlencode函數(shù)
可以把一個(gè)字典轉(zhuǎn)化為get請(qǐng)求參數(shù)
六、urllib.robotparser
使用較少,可作為了解
總結(jié)
到此這篇關(guān)于Python爬蟲之urllib庫詳解的文章就介紹到這了,更多相關(guān)Python urllib庫內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Python 3.x 判斷 dict 是否包含某鍵值的實(shí)例講解
今天小編就為大家分享一篇Python 3.x 判斷 dict 是否包含某鍵值的實(shí)例講解,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧2018-07-07使用IronPython把Python腳本集成到.NET程序中的教程
這篇文章主要介紹了使用IronPython把Python腳本集成到.NET程序中的教程,現(xiàn)在剛剛被微軟開源的.NET重新成為業(yè)界熱點(diǎn)、本文介紹了使Python和.NET交互的IronPython,需要的朋友可以參考下2015-03-03解決pycharm下載庫時(shí)出現(xiàn)Failed to install package的問題
很多小伙伴遇到pycharm下載庫時(shí)出現(xiàn)Failed to install package不知道怎么解決,下面小編給大家?guī)砹私鉀Q方法,需要的朋友參考下吧2021-09-09python小白練習(xí)題之條件控制與循環(huán)控制
Python 中的條件控制和循環(huán)語句都非常簡單,也非常容易理解,與其他編程語言類似,下面這篇文章主要給大家介紹了關(guān)于python小白練習(xí)題之條件控制與循環(huán)控制的相關(guān)資料,需要的朋友可以參考下2021-10-10python sklearn常用分類算法模型的調(diào)用
這篇文章主要介紹了python sklearn常用分類算法模型的調(diào)用,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2019-10-10Python pandas RFM模型應(yīng)用實(shí)例詳解
這篇文章主要介紹了Python pandas RFM模型應(yīng)用,結(jié)合實(shí)例形式詳細(xì)分析了pandas RFM模型的概念、原理、應(yīng)用及相關(guān)操作注意事項(xiàng),需要的朋友可以參考下2019-11-11