您好,登錄后才能下訂單哦!
這篇文章給大家分享的是有關(guān)Python爬蟲中urllib庫(kù)怎么用的內(nèi)容。小編覺得挺實(shí)用的,因此分享給大家做個(gè)參考,一起跟隨小編過來看看吧。
urllib庫(kù)是python內(nèi)置的一個(gè)http請(qǐng)求庫(kù),requests庫(kù)就是基于該庫(kù)開發(fā)出來的,雖然requests庫(kù)使用更方便,但作為最最基本的請(qǐng)求庫(kù),了解一下原理和用法還是很有必要的。
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.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測(cè)試網(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
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)行解碼。
如果我們需要發(fā)送復(fù)雜的請(qǐng)求,在urllib庫(kù)中就需要使用一個(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
設(shè)置代理
很多網(wǎng)站會(huì)檢測(cè)某一段時(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())
可以捕獲三種異常: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!')
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ù)
感謝各位的閱讀!關(guān)于“Python爬蟲中urllib庫(kù)怎么用”這篇文章就分享到這里了,希望以上內(nèi)容可以對(duì)大家有一定的幫助,讓大家可以學(xué)到更多知識(shí),如果覺得文章不錯(cuò),可以把它分享出去讓更多的人看到吧!
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。