python中urllib.request和requests的使用及區(qū)別詳解
urllib.request
我們都知道,urlopen()方法能發(fā)起最基本對(duì)的請(qǐng)求發(fā)起,但僅僅這些在我們的實(shí)際應(yīng)用中一般都是不夠的,可能我們需要加入headers之類的參數(shù),那需要用功能更為強(qiáng)大的Request類來構(gòu)建了
在不需要任何其他參數(shù)配置的時(shí)候,可直接通過urlopen()方法來發(fā)起一個(gè)簡(jiǎn)單的web請(qǐng)求
發(fā)起一個(gè)簡(jiǎn)單的請(qǐng)求
import urllib.requesturl=’https://www.douban.com’webPage=urllib.request.urlopen(url)print(webPage)data=webPage.read()print(data)print(data.decode(’utf-8’))
urlopen()方法返回的是一個(gè)http.client.HTTPResponse對(duì)象,需要通過read()方法做進(jìn)一步的處理。一般使用read()后,我們需要用decode()進(jìn)行解碼,通常為utf-8,經(jīng)過這些步驟后,最終才獲取到我們想要的網(wǎng)頁(yè)。
添加Headers信息
import urllib.requesturl=’https://www.douban.com’headers = { ’User-Agent’: ’Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/64.0.3282.186 Safari/537.36’, }response=urllib.request.Request(url=url,headers=headers)webPage=urllib.request.urlopen(response)print(webPage.read().decode(’utf-8’))
使用Request類返回的又是一個(gè)urllib.request.Request對(duì)象了。
通常我們爬取網(wǎng)頁(yè),在構(gòu)造http請(qǐng)求的時(shí)候,都需要加上一些額外信息,什么Useragent,cookie等之類的信息,或者添加代理服務(wù)器。往往這些都是一些必要的反爬機(jī)制
requests
通常而言,在我們使用python爬蟲時(shí),更建議用requests庫(kù),因?yàn)閞equests比urllib更為便捷,requests可以直接構(gòu)造get,post請(qǐng)求并發(fā)起,而urllib.request只能先構(gòu)造get,post請(qǐng)求,再發(fā)起。
import requestsurl=’https://www.douban.com’headers = { ’User-Agent’: ’Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/64.0.3282.186 Safari/537.36’,}get_response = requests.get(url,headers=headers,params=None)post_response=requests.post(url,headers=headers,data=None,json=None)print(post_response)print(get_response.text)print(get_response.content)print(get_response.json)
get_response.text得到的是str數(shù)據(jù)類型。
get_response.content得到的是Bytes類型,需要進(jìn)行解碼。作用和get_response.text類似。
get_response.json得到的是json數(shù)據(jù)。
總而言之,requests是對(duì)urllib的進(jìn)一步封裝,因此在使用上顯得更加的便捷,建議小伙伴們?cè)趯?shí)際應(yīng)用當(dāng)中盡量使用requests。
補(bǔ)充知識(shí):python中urllib.request.Request()與urllib.request.urlopen()區(qū)別
蟒蛇中urllib.request.Request()與urllib.request.urlopen()的區(qū)別:
相對(duì)于urllib.request.urlopen()來說urllib.request.Request是進(jìn)一步的包裝請(qǐng)求,下面是請(qǐng)求類的源碼示例:
class Request: # 主要看這塊,構(gòu)造函數(shù)中指明了Request進(jìn)一步包裝請(qǐng)求中可以傳遞的參數(shù)有(url,data,headers, # origin_req_host,unverifiable,method) def __init__(self, url, data=None, headers={}, origin_req_host=None, unverifiable=False, method=None): self.full_url = url self.headers = {} self.unredirected_hdrs = {} self._data = None self.data = data self._tunnel_host = None for key, value in headers.items(): self.add_header(key, value) if origin_req_host is None: origin_req_host = request_host(self) self.origin_req_host = origin_req_host self.unverifiable = unverifiable if method: self.method = method pass
我們可以這樣使用(以下是模擬有道字典翻譯發(fā)送的請(qǐng)求):
# 請(qǐng)求地址urlurl = 'http://fanyi.youdao.com/translate?smartresult=dict&smartresult=rule' # 請(qǐng)求頭request_headers = { ’Host’:’fanyi.youdao.com’, 'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.108 Safari/537.36',} # 發(fā)送給服務(wù)器的表單form_data = { 'i': word, 'from': 'AUTO', 'to': 'AUTO', 'smartresult': 'dict', 'doctype': 'json', 'version': '2.1', 'keyfrom': 'fanyi.web', 'action': 'FY_BY_REALTIME', 'typoResult': 'false'} # POST發(fā)送的data必須為bytes或bytes類型的可迭代對(duì)象,不能是字符串form_data = urllib.parse.urlencode(form_data).encode() # 構(gòu)造請(qǐng)求對(duì)象Requestreq = urllib.request.Request(url, data=form_data, headers=request_headers) # 發(fā)起請(qǐng)求response = urllib.request.urlopen(req)data = response.read().decode()print(data)
所以,總的來說,如果我們?cè)讷@取請(qǐng)求對(duì)象時(shí),不需要過多的參數(shù)傳遞,我么可以直接選擇urllib.request.urlopen();如果需要進(jìn)一步的包裝請(qǐng)求,則需要用urllib.request里。的urlopen()進(jìn)行包裝處理。
以上這篇python中urllib.request和requests的使用及區(qū)別詳解就是小編分享給大家的全部?jī)?nèi)容了,希望能給大家一個(gè)參考,也希望大家多多支持好吧啦網(wǎng)。
相關(guān)文章:
1. 在Android中使用WebSocket實(shí)現(xiàn)消息通信的方法詳解2. 淺談python出錯(cuò)時(shí)traceback的解讀3. ASP 信息提示函數(shù)并作返回或者轉(zhuǎn)向4. Python importlib動(dòng)態(tài)導(dǎo)入模塊實(shí)現(xiàn)代碼5. windows服務(wù)器使用IIS時(shí)thinkphp搜索中文無效問題6. 利用promise及參數(shù)解構(gòu)封裝ajax請(qǐng)求的方法7. python matplotlib:plt.scatter() 大小和顏色參數(shù)詳解8. .NET中l(wèi)ambda表達(dá)式合并問題及解決方法9. JSP數(shù)據(jù)交互實(shí)現(xiàn)過程解析10. Nginx+php配置文件及原理解析
