爬蟲之request模塊-創(chuàng)新互聯(lián)

一爬蟲簡介

成都創(chuàng)新互聯(lián)公司成立于2013年,先為翠屏等服務(wù)建站,翠屏等地企業(yè),進行企業(yè)商務(wù)咨詢服務(wù)。為翠屏企業(yè)網(wǎng)站制作PC+手機+微官網(wǎng)三網(wǎng)同步一站式服務(wù)解決您的所有建站問題。

概述

近年來,隨著網(wǎng)絡(luò)應(yīng)用的逐漸擴展和深入,如何高效的獲取網(wǎng)上數(shù)據(jù)成為了無數(shù)公司和個人的追求,在大數(shù)據(jù)時代,誰掌握了更多的數(shù)據(jù),誰就可以獲得更高的利益,而網(wǎng)絡(luò)爬蟲是其中最為常用的一種從網(wǎng)上爬取數(shù)據(jù)的手段。

網(wǎng)絡(luò)爬蟲,即Web Spider,是一個很形象的名字。如果把互聯(lián)網(wǎng)比喻成一個蜘蛛網(wǎng),那么Spider就是在網(wǎng)上爬來爬去的蜘蛛。網(wǎng)絡(luò)蜘蛛是通過網(wǎng)頁的鏈接地址來尋找網(wǎng)頁的。從網(wǎng)站某一個頁面(通常是首頁)開始,讀取網(wǎng)頁的內(nèi)容,找到在網(wǎng)頁中的其它鏈接地址,然后通過這些鏈接地址尋找下一個網(wǎng)頁,這樣一直循環(huán)下去,直到把這個網(wǎng)站所有的網(wǎng)頁都抓取完為止。

爬蟲的價值

互聯(lián)網(wǎng)中最有價值的便是數(shù)據(jù),比如天貓商城的商品信息,鏈家網(wǎng)的租房信息,雪球網(wǎng)的證券投資信息等等,這些數(shù)據(jù)都代表了各個行業(yè)的真金白銀,可以說,誰掌握了行業(yè)內(nèi)的第一手數(shù)據(jù),誰就成了整個行業(yè)的主宰,如果把整個互聯(lián)網(wǎng)的數(shù)據(jù)比喻為一座寶藏,那我們的爬蟲課程就是來教大家如何來高效地挖掘這些寶藏,掌握了爬蟲技能, 你就成了所有互聯(lián)網(wǎng)信息公司幕后的老板,換言之,它們都在免費為你提供有價值的數(shù)據(jù)。

robots.txt協(xié)議

如果自己的門戶網(wǎng)站中的指定頁面中的數(shù)據(jù)不想讓爬蟲程序爬取到的話,那么則可以通過編寫一個robots.txt的協(xié)議文件來約束爬蟲程序的數(shù)據(jù)爬取。robots協(xié)議的編寫格式可以觀察淘寶網(wǎng)的robots(訪問www.taobao.com/robots.txt即可)。但是需要注意的是,該協(xié)議只是相當于口頭的協(xié)議,并沒有使用相關(guān)技術(shù)進行強制管制,所以該協(xié)議是防君子不防小人。但是我們在學(xué)習爬蟲階段編寫的爬蟲程序可以先忽略robots協(xié)議。

爬蟲的基本流程

1.發(fā)送請求:通過相關(guān)模塊或者庫如瀏覽器一般向目標站點發(fā)送請求,即一個request,請求可以攜帶headers和參數(shù)等信息,然后等待服務(wù)器響應(yīng)。

2.獲取響應(yīng):服務(wù)器正常響應(yīng),會返回一個response,即頁面內(nèi)容,類型可能是html,json或者二進制數(shù)據(jù)(音頻視頻圖片等)

3.數(shù)據(jù)解析:響應(yīng)的字符串可以通過正則表達式或者beautifulSoup,xpath等解析器提煉出我們感興趣的數(shù)據(jù)

4.保存數(shù)據(jù):解析出的數(shù)據(jù)進行保存,可以存儲到文件中,也可以存儲到redies,mongdb等數(shù)據(jù)庫中

二 requests模塊

Requests是用python語言基于urllib編寫的,采用的是Apache2 Licensed開源協(xié)議的HTTP庫,Requests它會比urllib更加方便,可以節(jié)約我們大量的工作。一句話,requests是python實現(xiàn)的最簡單易用的HTTP庫,建議爬蟲使用requests庫。默認安裝好python之后,是沒有安裝requests模塊的,需要單獨通過pip安裝

2.1 基本語法

requests模塊支持的請求

import requests requests.get("http://httpbin.org/get") requests.post("http://httpbin.org/post") requests.put("http://httpbin.org/put") requests.delete("http://httpbin.org/delete") requests.head("http://httpbin.org/get") requests.options("http://httpbin.org/get") 

get請求

1 基本請求

import requests response=requests.get('https://www.jd.com/',)   with open("jd.html","wb") as f:     f.write(response.content)

2 含參數(shù)請求

import requests response=requests.get('https://s.taobao.com/search?q=手機') response=requests.get('https://s.taobao.com/search',params={"q":"美女"})

3 含請求頭請求

import requests response=requests.get('https://dig.chouti.com/',              headers={                    'User-Agent':'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/62.0.3202.75 Safari/537.36',                          }                       )

4 含cookies請求

import uuid import requests url = 'http://httpbin.org/cookies' cookies = dict(sbid=str(uuid.uuid4())) res = requests.get(url, cookies=cookies) print(res.text)

post請求

1 data參數(shù)

requests.post()用法與requests.get()完全一致,特殊的是requests.post()多了一個data參數(shù),用來存放請求體數(shù)據(jù) response=requests.post("http://httpbin.org/post",params={"a":"666"}, data={"name":"ccj"})

2 發(fā)送json數(shù)據(jù)

import requests res1=requests.post(url='http://httpbin.org/post', data={'name':'ccj'}) #沒有指定請求頭,#默認的請求頭:application/x-www-form-urlencoed print(res1.json())   res2=requests.post(url='http://httpbin.org/post',json={'age':"22",}) #默認的請求頭:application/json print(res2.json())

response對象

(1) 常見屬性

import requests respone=requests.get('https://sh.lianjia.com/ershoufang/') # respone屬性 print(respone.text) print(respone.content) print(respone.status_code) print(respone.headers) print(respone.cookies) print(respone.cookies.get_dict()) print(respone.cookies.items()) print(respone.url) print(respone.history) print(respone.encoding)

(2) 編碼問題

import requests response=requests.get('http://www.autohome.com/news') #response.encoding='gbk' #汽車之家網(wǎng)站返回的頁面內(nèi)容為gb2312編碼的,而requests的默認編碼為ISO-8859-1,如果不設(shè)置成gbk則中文亂碼 with open("res.html","w") as f:     f.write(response.text)

(3) 下載二進制文件(圖片,視頻,音頻)

import requests response=requests.get('https://cache.yisu.com/upload/information/20200217/57/4561.jpg') with open("res.png","wb") as f:     # f.write(response.content) # 比如下載視頻時,如果視頻100G,用response.content然后一下子寫到文件中是不合理的     for line in response.iter_content():         f.write(line)

(4) 解析json數(shù)據(jù)  

import requests import json   response=requests.get('http://httpbin.org/get') res1=json.loads(response.text) #太麻煩 res2=response.json() #直接獲取json數(shù)據(jù) print(res1==res2)

(5) Redirection and History

默認情況下,除了 HEAD, Requests 會自動處理所有重定向??梢允褂庙憫?yīng)對象的 history 方法來追蹤重定向。Response.history 是一個 Response 對象的列表,為了完成請求而創(chuàng)建了這些對象。這個對象列表按照從最老到最近的請求進行排序。 >>> r = requests.get('http://github.com') >>> r.url 'https://github.com/' >>> r.status_code 200 >>> r.history [<Response [301]>]

另外,還可以通過 allow_redirects 參數(shù)禁用重定向處理:

>>> r = requests.get('http://github.com', allow_redirects=False) >>> r.status_code 301 >>> r.history [] 

2.2 requests進階用法

代理

一些網(wǎng)站會有相應(yīng)的反爬蟲措施,例如很多網(wǎng)站會檢測某一段時間某個IP的訪問次數(shù),如果訪問頻率太快以至于看起來不像正常訪客,它可能就會會禁止這個IP的訪問。所以我們需要設(shè)置一些代理服務(wù)器,每隔一段時間換一個代理,就算IP被禁止,依然可以換個IP繼續(xù)爬取。

res=requests.get('http://httpbin.org/ip', proxies={'http':'110.83.40.27:9999'}).json() print(res)

免費代理

https://www.kuaidaili.com/free/

2.3 爬蟲案例

github的home頁

import requests import re #第一步: 請求獲取token,以便通過post請求校驗 session=requests.session() res=session.get("https://github.com/login") authenticity_token=re.findall('name="authenticity_token" value="(.*?)"',res.text)[0] print(authenticity_token) # 第二步 構(gòu)建post請求數(shù)據(jù) data={     "login": "yuanchenqi0316@163.com",     "password":"yuanchenqi0316",     "commit": "Sign in",     "utf8": "?",     "authenticity_token": authenticity_token     } res=session.post("https://github.com/session",data=data,headers=headers,cookies=cookies) with open("github.html","wb") as f:     f.write(res.content)

另外有需要云服務(wù)器可以了解下創(chuàng)新互聯(lián)cdcxhl.cn,海內(nèi)外云服務(wù)器15元起步,三天無理由+7*72小時售后在線,公司持有idc許可證,提供“云服務(wù)器、裸金屬服務(wù)器、高防服務(wù)器、香港服務(wù)器、美國服務(wù)器、虛擬主機、免備案服務(wù)器”等云主機租用服務(wù)以及企業(yè)上云的綜合解決方案,具有“安全穩(wěn)定、簡單易用、服務(wù)可用性高、性價比高”等特點與優(yōu)勢,專為企業(yè)上云打造定制,能夠滿足用戶豐富、多元化的應(yīng)用場景需求。

分享名稱:爬蟲之request模塊-創(chuàng)新互聯(lián)
標題來源:http://bm7419.com/article44/cdiehe.html

成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供網(wǎng)站制作、電子商務(wù)、品牌網(wǎng)站建設(shè)、網(wǎng)站內(nèi)鏈虛擬主機、標簽優(yōu)化

廣告

聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請盡快告知,我們將會在第一時間刪除。文章觀點不代表本網(wǎng)站立場,如需處理請聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時需注明來源: 創(chuàng)新互聯(lián)

搜索引擎優(yōu)化